user gets the object using only abstract class and interface By using the Factory Pattern, the user does not need to be aware of the various objects required for the composition of the target object and their combinations. </ Font>
Below is the sample code of the abstract Factory Pattern.
The class structure is as follows
class | Explanation |
---|---|
abstract factory.class |
Define abstract create method |
samFactoryA.class | Extend the factory Generate and combine the parts classes required to compose the target |
samFactoryB.class | Same as above |
interface face1 interface face2 |
Interface for parts |
parts1.class ~ parts4.class | Parts class required for the composition of the target product |
user(Main.class) | Check the operation |
The sample code below uses two factories Because abstract Factory Pattern makes it easy to create multiple factories There is a feature that improves the convenience of the user
factory.class
abstract class factory{
String msg;
int len;
factory(String msg){
this.msg = msg;
len =msg.length();
}
abstract String create();
}
samFactoryA.class
class samFactoryA extends factory{
samFactoryA(String msg){super(msg);}
String create(){
String partsA = new partsA().s;
String partsB = new partsB().s;
return partsA+super.msg+partsB;
}}
samFactoryB.class
class samFactoryB extends factory{
samFactoryB(String msg){super(msg);}
String create(){
String partsA = new partsA().s;
String partsB = new partsB().s;
String partsC = new partsC().s;
String partsD = new partsD().s;
return partsA+partsC + super.msg + partsD+partsB;
}}
interface_face1
interface face1{}
class partsA implements face1{String s="<<< ";}
class partsB implements face1{String s=" >>>";}
interface face2{}
class partsC implements face2{String s="[[[ ";}
class partsD implements face2{String s=" ]]]";}
user(Main.class)
public static void main(String[] args){
factory f1 = new samFactoryA("Hello java");
System.out.println(f1.create());
factory f2 = new samFactoryB("HELLO JAVA");
System.out.println(f2.create());
}}
Recommended Posts