1.FactoryMode (Factory mode)
Definition: Provides an interface for creating objects to facilitate the creation of objects.
2. Static Factory method model (static Factory mode)
Definition: For object creation, the static method is implemented inside the factory class.
Usage scenario: When subclasses of the base class are used less , and no more subclasses are added.
Disadvantage, when the subclass increases, it is necessary to modify the interior of the factory class, violating the opening and shutting principle.
Base class and subclass:
public interface Sender {void Send ();} Class Sendermail implements sender{@Overridepublic void Send () {//TODO auto-generated method StubSystem.out.println (" Send the message. ");}} Class Sendersms implements sender{ @Overridepublic void Send () {//TODO auto-generated method stub SYSTEM.OUT.PRINTLN ("Send SMS. ");}}
Static Factory mode:
Static Factory mode method: Generates objects through a factory-built method. Disadvantage: When the subclass of the base class is incremented, the method in the factory class needs to be modified. violates the open/closed principle (increases the expansion of the interface, reduces internal modifications) class Senderfactory {public static Sender Producemail () {return new Sendermail ();} public static Sender Producesms () {return new sendersms ();}}
Test:
public class Test {public static void main (string[] args) {//TODO auto-generated method stub Sender mail=senderfactor Y.producemail (); Mail.send (); Sender sms=senderfactory.producesms (); Sms.send ();}}
Run:
Send the message. Send a text message.
3. Abstract Factory mode (Factory)
Definition: For the creation of objects, it is given to the subclass factory of the abstract factory to implement.
Usage Scenario: When the subclass of the base class increases, I can increase the factory subclass to create objects that conform to the open and closed principle .
Abstract Factory:
Interface Senderfactory { Sender produce ();} Class Mailsenderfactory implements senderfactory{@Overridepublic Sender Produce () {//TODO auto-generated method Stubreturn new Sendermail ();}} Class Smssenderfactory implements senderfactory{ @Overridepublic Sender Produce () {//TODO auto-generated Method Stubreturn new Sendersms ();}}
Test:
public class Test {public static void main (string[] args) {//TODO auto-generated method stub Sender mail=new MailSend Erfactory (). produce (); Mail.send (); Sender sms=new smssenderfactory (). produce (); Sms.send ();}}
Run:
Send the message. Send a text message.
java-design mode (created)-"Factory mode"