Factory model:
Compared with the previous simple factory model, the factory model is more in line with the open and closed principle. The new object type is implemented by adding a factory class, rather than modifying the original factory class. Use a simple example of Lei Feng for comparison.
package simpleFactoryVSFactory;interface IXueLeiFeng { void sweep(); void wash();}class Student implements IXueLeiFeng { @Override public void sweep() { // TODO Auto-generated method stub System.out.println("Student sweep"); } @Override public void wash() { // TODO Auto-generated method stub System.out.println("Student wash"); }}class Volunteer implements IXueLeiFeng { @Override public void sweep() { // TODO Auto-generated method stub System.out.println("Volunteer sweep"); } @Override public void wash() { // TODO Auto-generated method stub System.out.println("Volunteer wash"); }}public class SimpleFactory { public static IXueLeiFeng createLeiFeng(String name) { IXueLeiFeng instance; if (name.equals("student")) { instance = new Student(); } else { instance = new Volunteer(); } return instance; } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub IXueLeiFeng leiFengA = createLeiFeng("student"); leiFengA.sweep(); leiFengA.wash(); IXueLeiFeng leiFengB = createLeiFeng("Not student"); leiFengB.sweep(); leiFengB.wash(); }}
The factory mode abstracts a factory interface and adds the object type. You only need to implement the factory interface and expand it.
package simpleFactoryVSFactory;interface IFactory { IXueLeiFeng createLeiFeng();}class StudentFactory implements IFactory { @Override public IXueLeiFeng createLeiFeng() { // TODO Auto-generated method stub return new Student(); }}class VolunteerFactory implements IFactory { @Override public IXueLeiFeng createLeiFeng() { // TODO Auto-generated method stub return new Volunteer(); }}public class Factory { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub IFactory iFactoryA = new StudentFactory(); IXueLeiFeng leiFengA = iFactoryA.createLeiFeng(); leiFengA.sweep(); leiFengA.wash(); IFactory iFactoryB = new VolunteerFactory(); IXueLeiFeng leiFengB = iFactoryB.createLeiFeng(); leiFengB.sweep(); leiFengB.wash(); }}
Head first
Factory mode vs Abstract Factory
In head first, the factory mode defines an abstract method to implement the subclass that inherits it, and delays the class Instantiation to the subclass.
Abstract Factory: defines an interface, which combines the creation methods of a bunch of related objects.
Factory features: they are used to encapsulate the creation of objects and help implement interface-oriented programming rather than implementation programming.