Article Directory
Definition and Types
Definition: The definition of a created object's interface
but let's decide which class to instantiate a class that implements this interface
factory method to instantiate postponed to allow subclass carried out
Type create type
Applicable scene
Creating an object requires a lot of repetitive code
The client (application layer) does not depend on how the product class instance is created, the realization details
A class to specify which objects created by its subclasses
advantage
Users only need to care about the desired product corresponding to the plant, without concern for the details of creating
Add a new product line with the principle of opening and closing, scalability
Software design principles used: Richter Substitution Principle opening and closing the principle of
using an object-oriented polymorphism
Shortcoming
The number of class too easy
Increase the complexity of the system increases the abstract and difficult to understand
Show
Create a Cake abstract class
package softwareDesign.coding.factoryMethod;
public abstract class Cake {
public abstract void produce();
}
chocolate cake
package softwareDesign.coding.factoryMethod;
public class CCake extends Cake{
@Override
public void produce() {
System.out.println("生产巧克力蛋糕");
}
}
Snow Cake
package softwareDesign.coding.factoryMethod;
public class SnowCake extends Cake{
@Override
public void produce() {
System.out.println("生产雪花蛋糕");
}
}
Create an abstract factory class
package softwareDesign.coding.factoryMethod;
public abstract class CakeFactory {
public abstract Cake getCakeFactory();
}
Create a Chocolate Cake Factory
package softwareDesign.coding.factoryMethod;
public class CCakeFactory extends CakeFactory{
@Override
public Cake getCakeFactory() {
return new CCake();
}
}
Create a snowflake cake production plant
package softwareDesign.coding.factoryMethod;
public class SnowCakeFactory extends CakeFactory {
@Override
public Cake getCakeFactory() {
return new SnowCake();
}
}
test:
package softwareDesign.coding.factoryMethod;
public class Test {
public static void main(String[] args) {
CakeFactory cakeFactory = new CCakeFactory();
Cake cake = cakeFactory.getCakeFactory();
cake.produce();
CakeFactory cakeFactory2 = new SnowCakeFactory();
Cake cake2 = cakeFactory2.getCakeFactory();
cake2.produce();
}
}
Combined with simple factory to understand
We look at the UML diagram
If expanded, adding a new type of cake and factories are just "in the outer Bubu", without touching the core code. It is easy to see the factory method is very cleverly solved the product group problem