Factory Method Pattern
In cases where you cannot create an instance with new, such as when the package is different, use the Factory Method Pattern to get an instance
The factory abstract class defines the skeleton to instantiate
A subclass of the factory abstract class creates an actual instance
user receives an instance through the factory abstract class
Design Pattarm MENU
This page has the following structure
If you just want to check the code, fly second
-Case where you cannot create an instance with new
・ Confirmation of Factory Method Pattern
Check with the following class structure
package name | class | Access modifier | Explanation |
---|---|---|---|
Default | user(Main.class) | public | Check the operation |
implement | sam.class | Default | nothing special |
java:package.implement.sam
package implement;
class sam{}
user(Main.class)
import implement.*;
public static void main(String[] args){
sam s = new sam();
}
result
python
sam cannot be resolved to a type
Because the access modifier of sam.class is Default It can only be accessed from the class that belongs to the package
Therefore, sam.class is completely independent from user and cannot be touched. For example, use the Factory Method Pattern in such cases
Check with the following configuration
package name | Access modifier | class | import | Explanation |
---|---|---|---|---|
framework | public | abstract samFramework.class | None | Abstract class of objects used by user |
framework | public | abstract factoryFramwork.class | None | Abstract class that defines instantiation |
implement | Default | sam.class | import framework.samFramework | user is sam()Use an instance of |
implement | public | factory.class | import framework.samFramework import framework.factoryFramework |
sam.Create an instance of class |
Default | public | user(Main.class) | import framework.samFramework import framework.factoryFramework import implement.factory |
Let's make a class
samFramework.class
package framework;
public abstract class samFramework{
public abstract void show();
}
factoryFramework.class
package framework;
public abstract class factoryFramework{
public abstract samFramework newInstance();
}
sam.class
package implement;
import framework.samFramework;
class sam extends samFramework {
public void show(){System.out.println("sam");}
}
factory.class
package implement;
import framework.factoryFramework;
import framework.samFramework;
public class factory extends factoryFramework {
public samFramework newInstance(){return new sam();}
}
user(Main.class)
import framework.factoryFramework;
import framework.samFramework;
import implement.factory;
class Main {
public static void main(String[] args){
factoryFramework factory = new factory();
samFramework sam = factory.newInstance();
sam.show();
}}
Recommended Posts