Factory method mode, factory Mode
1 factory model Introduction
1.1 Definition: defines an interface used to create objects so that the subclass can absolutely instantiate which class. The factory method delays the instantiation of a class to its subclass.
General class diagram of factory method mode:
In the factory model, abstract Product products are responsible for defining Product commonalities and implementing the most abstract definition of things. Creator creates classes for abstract classes, that is, abstract factories, how to create a product class is implemented by the factory ConcreteCreator.
1.2 advantages of the factory method model
- Good encapsulation and clear code structure.
- The scalability is excellent. When the product category is added, you can "embrace changes" only by modifying the specific factory category or extending a factory category ".
- Block product categories. The caller does not need to care about how the product class is implemented. The caller only needs to care about the product interfaces. As long as the interfaces remain unchanged, the upper-layer modules in the system do not need to change.
- Decoupling framework. The high-level module only needs to know the abstract class of the product, and does not need to care about other implementation classes.
1.3 Use Cases of the factory method model
2. Factory mode implementation
2.1 simple factory mode (static factory Mode)
Take a calculator as an example:
The entire process involves three objects, represented by a person (Program4), a calculator (represented by the OperationFactory class), a computing method (multiple calculation methods, addition, subtraction, multiplication, division, and so on), but all belong to the computing method, with a parent class Operation, add, subtract, multiply, and divide the inheritance override method ). The entire example class is as follows:
1 public class Program4 {2 public static void main (String [] args) {3 try {4 Dynamic partition = new partition (System. in); 5 6 System. out. println ("Enter the number A:"); 7 double numberA = Double. parseDouble (separator. nextLine (); 8 System. out. println ("select operator (+,-, *,/):"); 9 String strOperate = random. nextLine (); 10 System. out. println ("Enter the number B:"); 11 double numberB = Double. parseDouble (separator. nextLine (); 12 String strResult = ""; 13 14 if (strOperate! = "/" | NumberB! = 0) {15 Operation seconds; 16 seconds = OperationFactory. createOperate (strOperate); 17 bytes. setNumberA (numberA); 18 bytes. setNumberB (numberB); 19 20 strResult = String. valueOf (outputs. getResult (); 21 System. out. println ("Result:" + strResult); 22 23} else {24 System. out. println ("the divisor cannot be zero"); 25} 26 27 bytes. close (); 28} catch (Exception e) {29 throw new RuntimeException ("your input is incorrect:" + e. getMessage (); 30} 31} 32}
The calculator (factory) selects (generate) The calculation method to create the corresponding instance object according to the user's requirements. The user is required to participate in the creation process.
1 public class OperationFactory { 2 public static Operation createOperate(String operate) { 3 Operation oper = null; 4 switch (operate){ 5 case "+": 6 oper = new OperationAdd (); 7 break; 8 case "-": 9 oper = new OperationSub ();10 break;11 case "*":12 oper = new OperationMul ();13 break;14 case "/":15 oper = new OperationDiv ();16 break;17 }18 return oper;19 }20 }
1 public class Operation{ 2 private double numberA = 0; 3 private double numberB = 0; 4 5 public double getNumberA() { return numberA; } 6 7 public void setNumberA(double numberA) { this.numberA = numberA; } 8 9 public double getNumberB() { return numberB; }10 11 public void setNumberB(double numberB) { this.numberB = numberB; }12 13 public double getResult(){ 14 double result = 0;15 return result;16 }17 }18 19 class OperationAdd extends Operation{20 @Override21 public double getResult() {22 double result = 0;23 result = getNumberA () + getNumberB ();24 return result;25 }26 }27 28 class OperationSub extends Operation{29 @Override30 public double getResult() {31 double result = 0;32 result = getNumberA () - getNumberB ();33 return result;34 }35 }36 37 class OperationMul extends Operation{38 @Override39 public double getResult() {40 double result = 0;41 result = getNumberA () * getNumberB ();42 return result;43 }44 }45 46 class OperationDiv extends Operation{47 @Override48 public double getResult() {49 double result = 0;50 result = getNumberA () / getNumberB ();51 return result;52 }53 }
The disadvantage of a simple factory is that it does not comply with the "open and closed" principle. To add new features (computing methods), you need to modify the factory class (adding branches ).
2.2 multi-method mode
Is an improvement on the common factory method mode. In the common factory method mode, if the passed string is incorrect, the object cannot be created correctly, multiple factory method modes provide multiple factory methods to create objects respectively.
1 public class OperationFactory03 { 2 3 public Operation add(){ 4 return new OperationAdd(); 5 } 6 7 public Operation sub(){ 8 return new OperationSub (); 9 }10 11 public Operation mul(){12 return new OperationMul();13 }14 15 public Operation div(){16 return new OperationDiv();17 }18 }
1 public class FactoryTest { 2 3 public static void main(String[] args) { 4 5 OperationFactory03 factory03 = new OperationFactory03(); 6 Operation add = factory03.add(); 7 8 add.setNumberA(20); 9 add.setNumberB(10);10 double result = add.getResult();11 System.out.println(result);12 }13 }
2.3 static factory method mode
If the methods in multiple factory method modes are set to static, you can directly call them without creating an instance.
1 public class OperationFactory { 2 3 public static Operation add(){ 4 return new OperationAdd(); 5 } 6 7 public static Operation sub(){ 8 return new OperationSub (); 9 }10 11 public static Operation mul(){12 return new OperationMul();13 }14 15 public static Operation div(){16 return new OperationDiv();17 }18 }
1 // call class 2 public class FactoryTest {3 4 public static void main (String [] args) {5 6 Operation add = OperationFactory02.add (); 7 add. setNumberA (20); 8 add. setNumberB (10); 9 double result = add. getResult (); 10 System. out. println (result); 11 12} 13}
In general, the factory mode is suitable: when a large number of products need to be created and have common interfaces, they can be created through the factory method mode. In the preceding three modes, if the input string is incorrect, the object cannot be correctly created. The third mode does not need to instantiate the factory class. Therefore, in most cases, we will choose the third static factory method mode.
3. Abstract Factory Model
One problem with the factory method mode is that the creation of the class depends on the factory class. That is to say, if you want to expand the program, you must modify the factory class, which violates the closure principle. Therefore, from the design perspective, how can we solve certain problems? The abstract factory mode is used to create multiple factory classes. Once new functions need to be added, new factory classes can be directly added without modifying the previous code. Because the abstract factory is not very easy to understand, let's take a look at the figure first, and then it is easier to understand with the code.
Interface Class
1 public interface Sender {2 public void Send();3 }
Two implementation classes
1 public class MsgSender implements Sender{2 3 @Override4 public void Send() {5 System.out.println("this is msgsender");6 }7 }
1 public class MailSender implements Sender {2 3 @Override4 public void Send() {5 System.out.println("this is mailsender!");6 }7 }
Two factory types
1 public class SendmsgFactory implements Provider {2 3 @Override4 public Sender produce() {5 return new MsgSender();6 }7 }
1 public class SendmailFactory implements Provider {2 3 @Override4 public Sender produce() {5 return new MailSender();6 }7 }
Provides an interface
1 public interface Provider {2 public Sender produce();3 }
Test class
1 public class FactoryTest {2 public static void main(String[] args) {3 Provider provider = new SendmailFactory();4 Sender sender = provider.produce();5 sender.Send();6 }7 }
In fact, the advantage of this mode is that if you want to add a function: sending timely information, you only need to create an implementation class to implement the Sender interface, and at the same time make a factory class to implement the Provider interface, it's okay. You don't need to change the existing code. In this way, the scalability is good, that is, the dependency on abstraction is not dependent on the embodiment of specific principles.