23 design modes - source code

xiaoxiao2021-04-10  374

Package lq.test;

Import java.io. *; import java.util. *;

// ********* Created mode **************

// Factory Method 1 // 1 Specific constructor, and 2 constructed specific products constructed by subclasses Interface Product {}

// or I also provide a factory interface, which inherits it by this abstract class.

Abstract Class Factory {Abstract Public Product FMD ();

/ / I think this method is that it is a supplement to the FactoryMethod method //, for example, to assign a value for the generated object, calculated as a result of the generated object, the day value // and these are common, generated products The most important algorithm is still in FactoryMethod, // This method is just a secondary action, which is also a way of thinking, implementing the specific algorithm in one method // / I don't call this method directly, and use another method Package it, wait until a more flexible effect, and // Subcarpse required to achieve the factoryMethod // This method is a TemplateMethodPublic Product Creat () {Product PD = NULL;

System.out.Println ("Before Operation");

PD = fMD ();

System.out.println ("end operation");

Return Pd;}}

Class Product1 Implements Product {}

Class Factory1 Extends Factory {Public Product FMD () {Product Pd = New Product1 (); Return Pd;}}

// FACTROYMETHOD 2 // This way is simple and practical interface product productA {}

Interface factorya {product ();

Class Producta1 Implements Producta {}

Class Factorya1 Implements Factorya {Public Producta Create () {Producta PDA = NULL; PDA = New ProductA1 (); Return PDA;}}

// AbstractFactory // AbstractFactory and FactoryMethod Different lies in AbstractFactory created multiple products // feels that this mode is not big

// Of course, there can be more interface interface apDa {}

Interface apDB {}

Interface afactory {apDa createa (); apDb createb ();

Class APDA1 IMPLEments APDA {}

Class APDB1 IMPLEments APDB {}

// There are several interfaces, there are several corresponding methods Class Afactory1 Implements Afactory {public APDA CREATEA () {APDA APDA = NULL; APDA = New APDA1 (); Return APDA;}

Public APDB Createb () {APDB APDB = NULL; APDB = New APDB1 (); Return APDB;}

// / Builder // Generating a product is generated by generating components and assembly components, different layers of different products are different //, the components are assembled, and components generate abstraction into an interface method, and assembled methods use a TemplateMethod method

Interface cpda {}

Class cpda1 imports cpda {} interface builderi {void buildpart1 (); void buildpart2 ();

Void initpd (); cpda getpd ();

Abstract Class Buildra Implements Builderi {CPDA CPDA;

Public cpda getpd () {initpd ();

// Set buildpart1 (); buildpart2 (); BuildPart2 ();

Return cpda;}}

Class Builder Extends Buildra {Public Void BuildPart1 () {system.out.println (CPDA);

Public void buildpart2 () {system.out.println (cpda);

Public void initpd () {cpda = new cpda1 ();}}

// Realization of a simple generation product // 1ABSTRACT CLASS FY {Public Abstract Void Med1 ();

Static class fy1 extends fy {public void med1 () {}}

Public static fy getinstance () {fy fy = new fy1 (); return fy;

// fy fy = new fy1 () {// This anonymous internal class is static! ! // public void med1 () {//} //}; // returnif;}}

// 2Interface pdd {}

Class PDD1 IMPLEMENTS PDD {}

Abstract class fya {public static pdd getpd () {PDD PDD = New PDD1 (); return pdd;}}

// Prototype is clone in Java, including deep copy and shallow copy Class Cloneobja {public cloneobja myclone () {Return New Cloneobja ();}}

Class cloneobjb {public cloneobjb myclone () throws throwable {cloneobjb cobj = null; cobj = (cloneobjb) PCL (this); returno cobj;}

// deep-copy algorithm private Object pcl (Object obj) throws Throwable {ByteArrayOutputStream bao = new ByteArrayOutputStream (1000); ObjectOutputStream objo = new ObjectOutputStream (bao); objo.writeObject (obj);

BYTEARRAYINPUTSTREAM BAI = New ByteArrayInputStream (bao.toByteaRray ()); ObjectInputStream Obji = New ObjectInputStream (BAI);

Object objr = obji.readObject (); returnobjr;}}}

// Singleton // A class has only one object, such as a thread pool, a cacheclass singleton1 {public static singleleton1 instance = new singleleton1 ();

PRIVATE SINGLETON1 ()}

Public static singleleton1 getInstance () {return instance;}}

Class singleton2 {public static singleleton2 instance; private singleleton2 () {}

// public static singleleton2 getInstance () {// if (instance == null) {// instance = new singleleton2 (); //} /// Return Instance; ///}

Public static singleleton2 getinstance () {synchronized (Singleton2.class) {if (instance == null) {instance = new singleleton2 ();}}

Return Instance;}}

// ********** Structure mode **********

// adapter // Basic method has two, one is to use a reference to use inheritance // will transfer the interface that does not meet the standard to meet the standard interface, the modification of the interface is mainly the increase or decrease of the parameters, // Return value type Of course, there is also a method name / / feel that this is another representation of the package, and the package useful method package (modifying the function method in the method), // is encapsulated (the object where the function method is in the function method, passing Method for calling this object)

// Class Adaptee {PUBLIC VOID KK () {}}

Interface Targeta {String VV (INT I, INT K);}

Class Adaptera Implements Targeta {AdapteeA Ade;

Public Adaptera (Adapteea ADE) {this.ade = ade;

Public String VV (INT I, INT K) {// The specific business method is implemented in Adaptee, this method // only plays only to interface conversion // Call this method is by reference Ade.kk (); return null; }

// Use the inheritance form of class adapteeb {public void kk () {}}

Interface targetb {string VV (INT I, INT K);}

Class Adapterb ExtendB {Public String VV (INT I, INT K) {// Call this method is to inherit KK (); return null;}}

// proxyinterface subject {void request ();

Class RealSubject Implements Subject {Public Void Request () {// do the real business}}

Class Proxy IMPLEMENTS SUBJECT {SUBJECT SUBJECT

Public proxy (Subject Subject) {this.subject = Subject;}

Public void request () {system.out.println ("Do Something");

Subject.Request ();

System.out.println ("Do Something");}}

// bridge // feeling is a polymorphic implementation

Interface IMP {void Operation ();

Class Cimp1 Implements IMP {PUBLIC VOID OPERATION () {System.out.println ("1");}}

Class Cimp2 Implements Imp {Public Void Operation () {System.out.Println ("2");}}

Class Invoker {IMP = New CIMP1 (); public void infoke () {imp. galaxy ();}}

// composite

Interface component {void operation ();

Void Add (Component Component);

Void Remove (Component Component);

Class Leaf Implements Component {Public Void Operation () {System.out.println ("an Operation");}

Public Void Add (Component Component) {throw new unsupportedOperationException ();

Public void remove (Component Component) {throw new unsupportedOperationException ();}}

Class Composite Implements Component {List Components = New ArrayList ();

Public void Operation () {component component = null;

ITerator it = components.iterator (); while (it.hasnext ()) {// Doesn't know that this Component object is LEAF or composite, // If it is Leaf, you can implement it directly. If it is Composite, continue recursive call Component = ( IT.NEXT (); component.operation ();}}

Public Void Add (Component Component) {Components.Add (Component);

Public void remove (Component Component) {Components.remove (Component);}}

// Decorator // When an class is expanded, I can use inheritance, but not flexible enough, so the additional form is selected, reference and inheritance can live a certain ability to use the object, and Using reference will be more flexible // We must ensure that the additional function is added rather than modifications, otherwise only rewrite methods, or use new methods // Note that CONCRETE can directly New, // and Decorator need to use An additional Decorator object can generate an object // use object package, and multiple elements can be used on the public interface // Decorator chain

Interface componenta {void operation ();

Class componenta {public void Operation () {system.out.println ("do something");}}

Class Decorator Implements Componenta {Private Componenta Component

Public Decorator (Componenta Component) {this.component = component;

Public void Operation () {// do something before

Component.operation ();

// do something at}}}

// Facade // Very practical design mode, I can provide an interface to the exterior

Class Obj1 {public void OPE1 () {} public void OPE2 () {}}

Class Obj2 {public void OPE1 () {} public void OPE2 () {}} class facade {// I got a simple and clear interface public void fdMethod () {obj1 obj1 = new obj1 (); obj2 Obj2 = new Obj2 ();

Obj1.ope1 (); obj2.ope2 ();}}

// flyweight // empty

// ********** behavioral mode *************

// CHAIN ​​OF RESPONSIBILITY / / A similar form of Decorator is similar, // Decorator is to add functions over the original method, and // chain is the judgment signal if it is not currently processed, then the next node processing / / I can use the IF branch to achieve the same effect, but not flexible, each node on the chain can be replaced, relative // ​​is more flexible, we can design the interface to achieve a node's income operation, which is more convenient Effect // This is a chain structure, have you ever thought about using a ring structure

Interface Handler {Void Handrequest (intiGnal);

Class Chandler1 Implements Handler {Private Handler Handler

Public Chandler1 (Handler Handler) {this.handler = Handler;}

Public void handrequest (int signal) {if (signal == 1) {system.out.println ("Handle Signal 1");} else {handler.handRequest (Signal);}}}

Class Chandler2 Implements Handler {Private Handler Handler

Public Chandler2 (Handler Handler) {this.handler = Handler;}

Public void handrequest (intiGNAL) {if (signal == 2) {system.out.println ("Handle Signal 2");} else {handler.handrequest (signal);}}}

Class Chandler3 Implements Handler {Public Void HandRequest (Int Signal) {if (Signal == 3) {System.out.Println ("Handle Signal 3");} else {throw new error ("can't Handle Signal); }}}

Class chainclient {public static void main (string [] args) {handler h3 = new chandler3 (); handler h2 = new chandler2 (h3); handler h1 = new char1 (h2);

H1.handRequest (2);}}

// Interpreter // feels similar to Composite, but he is a partial part of the terminus and non-ending

// Template Method

Abstract Class TemplateMethod {Abstract Void AMD1 ();

Abstract void AMD2 ();

// This method is a Template method method public void TMD () {AMD1 (); AMD2 ();}}

//State

// Standard // Status and operation should not be coupled together Class Contexta {Private State St; Public Contexta (INT NST) {ChangestFromnum (NST);

Public void changestfromnum (int NST) {if (nst == 1) {st = new cStatea1 ();} else if (nst == 2) {st = new cStatea2 ();}

Throw new error ("badst");}

Void Request () {st.handle (this);}}

Interface State {void Handle (Contexta Context);

Class cStatea1 Implements State {public void Handle (CONTEXTA Context) {system.out.println ("State 1"); // may change the status during a state process, such as open this effect immediately // context .changestfromnum (2);}}

Class cStatea2 Implements State {Public Void Handle (Contexta Context) {System.Out.println ("State 2");}}

// Factory type / / Different State is generated according to status

// Class StateFactory {// public static state getStateInstance (int Num) {// state st = null; //// i == 1) {// st = new cStatea1 (); //} // else IF (NUM == 2) {// st = new cStatea2 (); //} //// Return st; //} //}

// strategy // is similar to Bridge, is a polymorphic representation

// Visitor // Bidirectional reference, use another class to call your own method, access your own data structure interface visitor {void visitelement;}

Class Cvisitor Implements Visitor {Public Void VisiteLement (Elementd Element) {Element.Operation ();}}

Interface Elementd {Void Accept (Visitor Visitor);

Void Operation ();

Class Celementd Implements Elementd {Public Void Accept (Visitor Visitor) {visitor.visiteLement (this);}

Public void operation () {// actual operation here}}}

Class clientd {public static void main () {Elementd Elm = new classd (); visitor vis = new cvisitor ();

Vis.VisiteLement (ELM);}}

// orthhotr // Use iterators to order the data structure of a class

Interface structure {interface itratora {void first ();

Boolean HaseLement ();

Object next ();

}

Class structure {object [] objs = new object [= new object [= new object [];

// Use the internal class to have a complete access to the data structure of Struture1, Class Iteratra1 Implements Iteratra {INDEX = 0; public void first () {index = 0;}

Public Boolean Haselement () {Return INDEX <100;}

Public Object next () {object obj = null;

IF (HaseLement ()) {Obj = Objs [Index]; Index ;}

Return Obj;}}}

//Meditor

Class a1 {public void Operation1 () {} public void operation2 () {}}

Class a2 {public void Operation1 () {} public void operation2 () {}}

Class Mediator {A1 A1; A2 A2;

Public Mediator (A1 A1, A2 A2) {THIS.A1 = A1; THIS.A2 = A2;

}

// If I want to implement this feature, I may put him in A1 // But this coupling big, I don't want to appear in A2 object in A1, // I use Mediator as a mediation public void mmed1 () { A1.Operation1 (); A2.Operation2 ();

Public void mmed2 () {a2.operation1 (); a1.Operation2 ();}}

// command // I think it is to convert the method into a class

Class receiver {public void action1 () {}

Public void action2 () {}}

Interface command {void execute ();

Class CCommand1 Implements Command {Private Receiver;

Public CCommand1 (Receiver Receiver) {this.Receiver = Receiver;}

Public void execute () {receiver.Action1 ();}}

Class CCommand2 IMPLEMENTS Command {Private Receiver;

Public CCommand2 (Receiver Receiver) {this.Receiver = Receiver;}

Public void execute () {received.Action2 ();}}

// Observer // See this mode does not use // But if I have a thread monitoring subject, if there is a change in Subject //, change the status of Observer, and use some operations, so there is actual The meaning of // Observer has similar places, there are two-way references // Subject can register a lot of OBServer

Interface SubjectB {Void Attach (Observer Observer);

Void Detach (Observer Observer);

Void mynotify ();

Int getState ();

Void setState;}

Class SubjectB1 Implements = new arraylist (); int 2;

Public void attach (observer observer) {OBSERVERS.ADD (Observer);

Public void detach (observer observer) {OBSERVERS.Remove (Observer);} public void mynotify () {Observer Observer = null; itrator it = Observers.ITerator ();

While (it.hasnext ()) {Observer = (Observer) it.next (); observer.Update ();}}

Public int getState () {return state;}

Public void setState (int 2) {this.state = state;}}

Interface Observer {void update ();

Class Observer1 Implements Observer {SubjectB Subject; int State;

Public Observer1 (Subjectb Subject) {this.subject = Subject;}

Public void update () {this.State = Subject.getState ();}

Public void Operation () {/ / Some state-based operations}}}

//Memento // feel that there is no big use in this mode

Class Memento {Int State;

Public int getState () {return state;}

Public void setState (int 2) {this.state = state;}}

Class Originator {Int State;

Public void setmeneneto {state =% gTState ();

Public Memento CreateMemento () {Memento MEMENTO = New Memento (); Memento.SetState (1); Return Memento;

Public int getState () {return state;}

Public void setState (int 2) {this.state = state;}}

Class Caretaker {MEMENTO MEMENTO;

Public void savermeneneto {this.memento = memento;}

Public Memento RetrieveMemento () {Return MEMENTO;}}

// The program is ultimately executed in order, is a splicing of different classes to splicing from the unhealthy operation, and the reference is implemented, and I // is equivalent to access the data structure and method. The ability, this is similar to the interior //, for example, I want to extract one of a class in a class, because this method relies on the data and other methods of this class // directly removed the code. But if we have a reference to such objects, it is nothing to do with the written //, so we have a reference to remove this method out of the public class tt1 {public static void main (string [] args) {} }

转载请注明原文地址:https://www.9cbs.com/read-133486.html

New Post(0)