Creational_Abstract Factory
β Abstract Factory
- similar to factory,
- but with a focus on the client
add
clientto factory pattern- interface creates the related classes instance
- ππ» can hide which
concrete productto the client
β Diagram
π ShipFactory example
Factory π AbstractFactory
- 곡ν΅μ : make creation of instance abstract with instance
- Factory: hide the creation of instance in concrete factory
- focus more on how to implement factory, interitance
- move instance creation process to concrte factory class
- ππ» defines an interface for creating an object, but lets subclasses (or a factory class) decide which class to instantiate
π create one product
- AbstractFactory: client does not have to see the concrete factory
- focus more on how to use factory, composition
- create related instances without relying on a concrete class
- ππ» interface for creating families of related objects without specifying their concrete classes.
- π multiple related products
1
2
3
4
5
6
7
8
9
10
π Factory
CarFactory β Mercedes or Kia
π Abstract Factory
GUIFactory
ββ createButton()
ββ createCheckbox()
WindowsFactory β WindowsButton + WindowsCheckbox
MacFactory β MacButton + MacCheckbox
π
βοΈ Abstract product Interface
1
2
3
4
5
6
7
8
interface Button {
//method that button can perform
press();
}
interface Checkbox {
tick();
}
βοΈ Concete products
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class WindowsButton implements Button {
//override method
press();
}
class MacButton implements Button {
//override method
press();
}
class WindowsCheckbox implements Checkbox {
//override method
tick();
}
class MacCheckbox implements Checkbox {
//override method
tick();
}
βοΈ Abstract Factory interface
1
2
3
4
interface GUIFactory {
Button createButton();
Checkbox createCheckbox();
}
βοΈ Concete Factory
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class WindowsFactory implements GUIFactory {
public Button createButton() {
return new WindowsButton();
}
public Checkbox createCheckbox() {
return new WindowsCheckbox();
}
}
class MacFactory implements GUIFactory {
public Button createButton() {
return new MacButton();
}
public Checkbox createCheckbox() {
return new MacCheckbox();
}
}
βοΈ Client
1
2
Button windowButton = new WindowsFactory().createButton();
Checkbox windowCheckbox = new WindowsFactory().createCheckbox();
π οΈ
- in
javax.xml.parsers DocumentBuilderFatoryto create xml
1
2
3
4
5
6
public static void main(String[[ args) throws ParserConfigurationException, IOException, SAXException{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new File("src/main/resource/config.xml"));
System.out.println(document.getDocumentElement());
}
FactoryBean<T>
This post is licensed under CC BY 4.0 by the author.


