Create mode
// FactoryMethod mode example
Package pattern.a.factorymethod;
Interface product {void operation ();
}
Class Conproduct1 Implements Product {// Different implementations can have different product operations public void operation () {}
}
Class Conproduct2 Implements Product {// Different implementations can have different product operations public void operation () {}
}
Interface factory {products;
Void Operation1 ();
class ConFactory1 implements Factory {// different classes of entities in the field can create a product is not a method of creating public Product CreateProduct () {Product product = new ConProduct1 (); operation1 (); return product;} public void operation1 () { }
Public static factory getFactory () {return new confactory1 ();}}
class ConFactory2 implements Factory {// different classes of entities in the field can create a product is not a method of creating public Product CreateProduct () {Product product = new ConProduct2 (); operation1 (); return product;} public void operation1 () { }
// public static factory getFactory () {return new confactory2 ();}}
Public class factorymethod {public static void main (string [] args) {factory factory = confactory1.getFactory (); product product = factory.createproduct (); product.operation ();}}
*********************************************************** ********************
// Abstract example // I think this mode is different from FactoryMethod is the number of created products.
Package pattern.a.abstractfactfactory;
// Product A interface and implementation interface productA {}
Class Producta1 Implements Producta {}
Class Porducta2 Implements Producta {}
// Product B interface and implementation interface productb {}
Class ProductB1 Implements ProductB {}
Class ProductB2 Implements ProductB {}
// Engineering and factory implementation interface factory {products; productA ();
}
1 1 // plant products generated class ConFactory1 implements Factory {public ProductA CreateA () {return new ProductA1 ();} public ProductB CreateB () {return new ProductB1 ();}} // 2 plants produce 2 product class ConFactory2 Implements factory {public producta createa () {return new porducta2 ();} public productb createb () {return new productb2 ();}}
Class confactory {}
Public class abstractFactory {
Public static void main (string [] args) {// 1 factory generates 1 type of product Factory Factory1 = new configuration1 (); productA a1 = factory1.createa (); productb b1 = factory1.createb (); // 2 factory generated 2 types of products Factory Factory2 = new confactory1 (); productA a2 = factory2.createa (); productB b2 = factory2.createb ();}}
*********************************************************** ********************
// The purpose of the example // mode of the builder mode is to separate the details of the details and parts of the part !!! The brothers are high
Package Pattern.a.builder;
class director {// construct stored in a separate logical public attention logic assembly missing Product construct (Builder builder) {builder.buildPart1 (); builder.buildPart2 (); operation (); Product product = builder.retrieveProduct (); } public void operation () {}}
Class product {}
Interface Builder {void Buildpart1 (); Void Buildpart2 (); Product RetrieveProduct ();
Class Conbuilder1 Implements Builder {Public Void Buildpart1 ()} public void Buildpart2 ()} public product retrieveproduct () {Return NULL;}}
Class Conbuilder2 Implements Builder {Public Void Buildpart1 () {} Public Void Buildpart2 ()} public product retrieveproduct () {Return null;}} public class builderpattern}
Public static void main (string [] args) {}}
*********************************************************** ********************
// Singleton mode example
Package pattern.a.singleton;
// a simple form class SingletonExample {private static SingletonExample instance; private SingletonExample () {} public static SingletonExample getInstance () {if (instance == null) {instance = new SingletonExample ();} return instance;} synchronized public static SingletonExample getInstance1 () {if (instance == null) {instance = new SingletonExample ();} return instance;} public static SingletonExample getInstance2 () {synchronized (SingletonExample.class) {if (instance == null) {instance = NEW SINGLETONEXAMPLE ();}} Return Instance;}}
// Initialization generated only once when using the class loader for class SingletonExample2 {private static SingletonExample2 instance = new SingletonExample2 (); private SingletonExample2 () {} public static SingletonExample2 getInstance () {return instance;}}
Public class singletonpattern {
Public static void main (string [] args) {}}
*********************************************************** ********************
// Prototype mode example
Package pattern.a.prototype;
Interface Prototype {Prototype myclone ();
Class Conprototype1 Implements Prototype {Private String A; Public Conprototype1 (String a) {this.a = a;} public prototype myclone () {return new conprototype1 (a);}}
class ConPrototype2 implements Prototype {private int b; public ConPrototype2 (int b) {this.b = b;} public Prototype myclone () {return new ConPrototype2 (b);}} public class PrototypePattern {public static void main (String [] ARGS) {prototype instimation = new conprototype1 ("teststr1"); prototype inst2 = null; inst2 = instimeta
*********************************************************** ********************
Structural mode
// Adapter mode example
Package pattern.b.adapter;
// Adapt to interface target1 {void request ();
Class AdapteE1 {Public Void SpecRequest () {}
}
Class Adapter1 Extends Adaptee1 Implements Target1 {
Public void request () {super.specrequest ();
}
// object adaptation
Interface Target2 {void request ();
}
Class adaptee2 {
Public void SpecRequest () {}
}
Class Adapter2 Implements Target2 {
Private adaptee2 adaptee; public adapter2 {this.adaptee = adaptee;} public void request () {adaptee.specRequest ();
}
Public class adapterpattern {
Public static void main (string [] args) {}}
*********************************************************** ********************
// Proxy mode example
Package Pattern.b.Proxy;
Interface Subject {void request ();
// Virtually handled the request to Class RealSubject Implements Subject {public void request () {system.out.println ("real access");}}
// proxySubject is a class with the user interacting with the user is the agent // of the agent // above the processing function. You can do before, for example, if you can verify whether the request is processed. class ProxySubject implements Subject {private RealSubject real; public ProxySubject (RealSubject real) {this.real = real;} // public void request () {preRequest (); real.request (); afterRequest ();} private void preRequest ( ) {} Private void afterRequest () {}} // java itself provides an agent class using reflex mechanism
Public class proxypattern {
Public static void main (string [] args) {}
}
*********************************************************** ********************
// Composite mode example // In the user's perspective, it doesn't know if it is separate or conforming to call the interface level method Operation.
Package Pattern.b.composite;
Import java.util.Arraylist; import java.util.ITerator; import java.util.list;
// Safety mode Only part of the features of the interface only Leaf and Composite have different feature interface component1 {public void operation ();}
Class Leaf1 Implements Component1 {public void Operation () {system.out.println ("this is the leaf1");}}
class Composite1 implements Component1 {private List components; public Composite1 () {components = new ArrayList ();} public void operation () {Iterator it = components.iterator (); Component1 com = null; while (it.hasNext ()) {Com = (Component1) it.next (); com.operation ();}} public void addcomponent (Component1 COM) {Components.Add (COM);} public void recaponent (int index) {Components.Remove (Index) }}
// Transparent mode interface definition All Functions Leaf may use an empty method or throw an exception to write a layer of abstraction class to write a default implementation method (extremely empty or abnormal)
Interface component2 {public void operation (); public void address; public void removonent (int index);}
Class Leaf2 Implements Component2 {Public Void Operation () {system.out.println ("this is the leaf1");} // This use air method public void address (Component2 COM) {} // This use does not support exception PUBLIC VOID removeComponent (int index) {throw new UnsupportedOperationException ();}} class Composite2 implements Component2 {private List components; public Composite2 () {components = new ArrayList ();} public void operation () {Iterator it = components.iterator () Component2 COM = NULL; While (it.hasnext ()) {com = (component2) it.next (); com.operation ();}} public void address (component2 com) {components.add (com);} Public void RemoveComponent (int index) {components.remove (index);}}
// You can also use an abstract class
Abstract Class Abstract2 {public void Operation () {} public void addcomponent (component2) {} Abstract public void removonent (int index);}
Public class compositePATTERN {
Public static void main (string [] args) {}}
*********************************************************** ********************
// FlyWight mode example / / Separate sharing common property with different attributes and different attributes are performed by external incoming specific operations
Package Pattern.b.FlyWeight; Import Java.util.hashmap; Import Java.util.map;
// 1 There is no way to pass OBJ.Value mode 2 Method 3 that does not change attribute 3 cannot reset attributes through inheritance, this object is Immutable Unmese Final Class State {Private String Value = NULL; public state (string value) {THIS. Value = value;} public string getValue () {return value;}}
Interface flyweight {void Operation (String ExtrinsicState);
Class Conflyweight1 Implements FlyWeight {// State Indicates the internal status of the enjoys // or the constructor is incorporated into the private state state = new state ("state1"); // OUT is the external state of the external transmission of the external state public void Operation String out) {/ Use external status and internal status to perform Operation operation system.out.Println ("ConflyWeight1:" Out State.getValue ());}}}}}}}}}}}}}}}}}}}}}}}}}}} // = new state ("state2"); public void Out (String out) {system.out.println ("conflyweight2:" state.getValue () out);}}
class FlyweightFactory {Map flyweights = new HashMap (); public Flyweight getFlyweight (String key) {if (flyweights.containsKey (key)) {return (Flyweight) flyweights.get (key);} else {// write here casually Flyweight flyweight = null; if (key.charAt (key.length () - 1) == '1') {flyweight = new ConFlyweight1 (); flyweights.put (key, flyweight);} else {flyweight = new ConFlyweight2 ( Flyweights.put (key, flyweight);}}}}
public class FlyweightPattern {public static void main (String [] args) {FlyweightFactory factory = new FlyweightFactory (); Flyweight flyweight1a = factory.getFlyweight ( "flytest1"); flyweight1a.operation ( "outparam1");}}
*********************************************************** ********************
// Bridge mode example // Take an operation to a reference to a reference to the specific operation of another object to make so easy to expand
Package Pattern.b.bridge;
Interface implementor {void realoperty ();
class ConImplementor1 implements Implementor {public void realOperation () {System.out.println ( "do the real operation1");}} class ConImplementor2 implements Implementor {public void realOperation () {System.out.println ( "do the real operation2" }}
Abstract Class Abstract {Protected Implementor Imp; Public Abstract (Implementor IMP) {this.imp = IMP;} Protected Void Med0 () {} Abstract Public Void Operation ();
Class Conabstraction Extends Abstract {Public Conabstraction (Implementor IMP) {Super (IMP);} PUBLIC VOID OPERATION () {MED0 (); Imp.RealOperation ();}}
Public class bridgepattern {public static void main (string [] args) {typementor imp = new constractor1 (); abstract abs = new conniction (IMP); ABS.Operation ();}}
*********************************************************** ********************
// Decorator mode example
Package Pattern.b.Decorator;
// Source Parts and Metal Camel Interface Component {void Operation ();
Class Concomponent Implements Component {Public Void Operation () {System.out.println ("The Begin Operation);}}
/ / No method for assigning value to Component So, this class is not an abstract method is not like let this class has an instance Abstract Class Dotor Implements Component {Private Component Component; public void Operation () {Component.Operation }}
Class Condecotor1 Extends Docotor {Private Component; PUBLIC COMPONENT {SUBLIC VOID OPERATION () {Super.Operation () {Super.operation (); // !! Note Here here provides a function added // Here It is the core part of Decorator is not a modification function but adds a function to the interface / / method of a Component incoming decorative class call object to add functions to the function of the interface method to re-implement the function of the interface method MED0 (); out.println ( "1");}} class ConDecotor2 extends Decotor {private Component component; public ConDecotor2 (Component component) {this.component = component;} public void operation () {super.operation (); med0 (); } Private void Med0 () {system.out.println ("2");}}
// Class
Public class decoratorPattern {public static void main (string [] args) {// Note The starting position is from a ConComponent !! Component Component = New Condecotor2 (New Concomponent ()); Component.Operation (); }
*********************************************************** ********************
// Facade example // The logic of the package and subsystem interaction in the method of the sub-system is built on the subsystem.
Package Pattern.b.Facade;
Class exa1 {public void medium () {}}}
Class exa2 {public void themed () {}}
// This is an example of a simple Facade method class facade {public void faced () {exa1 exa1 = new exa1 (); exa1.med0 (); exa2 exa2 = new exa2 (); exa2.Themed ();} }
Public class facadepattern {public static void main (string [] args) {}}
*********************************************************** ********************
Behavior mode
// Command mode example // Feel a class method to disperse abstraction into an interface method Note Parameters and return values to be consistent // Each Command package is an operation.
Package Pattern.c.command;
// This is a logical true realization location class receiver {public void media ()} public void media ()}} interface command {// Abstract into a unified interface method is limitless void execute ();
Class Concommand1 Immman; Public Concommand1 (Receiver) {this.Receiver = Receiver;} PUBLIC VOID EXECUTE () {receiver.med1 ();}}
Class Concommand2 Implements Command {Private Receiver; public concommman {this.receiver = receiver;} public void execute () {receiver.med2 ();}}
Class Invoker {Private Command Command; Public Invoker (Command Command) {this.command = Command;} PUBLIC VOID ACTION () {Command.execute ();}}
public class CommandPattern {public static void main (String [] args) {Receiver receiver = new Receiver (); // generates a command Command command = new ConCommand1 (receiver); Invoker invoker = new Invoker (command); invoker.action ( }}
*********************************************************** ********************
// strategy mode example // strategy encapsulated algorithm
Package Pattern.c.strategy;
Interface statne {void stmed ();
Class consTrategy1 {public void stmed () {}}
Class constrategy2 {public void stmed () {}}
Class Context {Private Strategy; PUBLIC CONTEXT (Strategy) {this.strategy = strategy;} public void conteterface () {strategy.stmed ();}}
Public class statulegypattern {public static void main (string [] args) {}}
*********************************************************** ********************
// state mode example // Pack the Assistant in a state and state in PATE
Package Pattern.c.state;
class Context {private State state = new CloseState (); public void changeState (State state) {this.state = state;} public void ruquest () {state.handle (this);}} interface State {void handle (Context context }
/ / Indicates Open Status Class OpenState Implements State {Public Void Handle (CONTEXT Context) {System.out.Println ("Do Something for Open"); Context.ChangeState (New CloseState ());}}
/ / Direction Turning State CLASESTATATE IMPLEments State {Public Void Handle (CONTEXT Context) {System.out.Println ("Do Something for Open"); context.changestate (New OpenState ());}}
Public class statepattern {public static void main (string [] args) {}}
*********************************************************** ********************
// Visitor mode example // two-way incoming
Package Pattern.c.visitor; import java.util. *;
Interface visitor {Void VisitconElementa; Void VisitConElementB (CONELEMENTB CONELEMENTB);}
class ConVisitor1 implements Visitor {public void visitConElementA (ConElementA conElementA) {String value = conElementA.value; conElementA.operation (); // do something} public void visitConElementB (ConElementB conElementB) {String value = conElementB.value; conElementB.operation ( ); // do something}}}
class ConVisitor2 implements Visitor {public void visitConElementA (ConElementA conElementA) {String value = conElementA.value; conElementA.operation (); // do something} public void visitConElementB (ConElementB conElementB) {String value = conElementB.value; conElementB.operation ( ); // do something}}}
Interface Element {Void Accept (Visitor Visitor);
class ConElementA implements Element {String value = "aa"; public void operation () {} public void accept (Visitor visitor) {visitor.visitConElementA (this);}} class ConElementB implements Element {String value = "bb"; public void Operation () {} public void accept (visitor visitor) {visitor.visitconelementb (this);}}
class ObjectStructure {private List Elements = new ArrayList (); public void action (Visitor visitor) {Iterator it = Elements.iterator (); Element element = null; while (it.hasNext ()) {element = (Element) it. Next (); element.accept (visitor);}}}} public void address {Elements.add (element);}}
public class VisitorPattern {public static void main (String [] args) {ObjectStructure objs = new ObjectStructure (); objs.add (new ConElementA ()); objs.add (new ConElementA ()); objs.add (new ConElementB ( )); Objs.action (new convisitor1 ());}}
*********************************************************** ********************
// OBSERVABLE mode example
Package Pattern.c.observable; import java.util. *;
Class State {}
Interface Subject {Void Attach (Observer Observer); void mynotify (); state getState (); void setState;}
class ConSubject implements Subject {List observers = new ArrayList (); State state = new State (); public void attach (Observer observer) {observers.add (observer);} public void detach (Observer observer) {observers.remove (observer } Public void mynotify () {ipserator (); observer observer = null; while (it.hasnext ()) {Observer = (observer) it.next (); Observer.Update ();} } Public state getState () {return state;} public void setState (statest) {this.state = state;}} interface observer {void update ();
class ConObserver1 implements Observer {private Subject subject; public ConObserver1 (Subject subject) {this.subject = subject;} public void update () {State state = subject.getState (); // do something with state}}
class ConObserver2 implements Observer {private Subject subject; public ConObserver2 (Subject subject) {this.subject = subject;} public void update () {State state = subject.getState (); // do something with state}}
Public class observablepattern {public static void main (string [] args) {}}
*********************************************************** ********************
// mediator mode example
Package pattern.c.mediator;
Public interface colleague {void setState; string getState (); void change (); void action ();
Package pattern.c.mediator;
public class ConColleague1 implements Colleague {private String state = null; private Mediator mediator; public void change () {mediator.changeCol1 ();} public ConColleague1 (Mediator mediator) {this.mediator = mediator;} public void setState (String state) {This.State = state;} public string getState () {return state;} public void action () {system.out.println ("this 2 and the state is" state);}} package pattern.c.mediator ;
public class ConColleague2 implements Colleague {private String state = null; private Mediator mediator; public ConColleague2 (Mediator mediator) {this.mediator = mediator;} public void change () {mediator.changeCol2 ();} public void setState (String state) {This.State = state;} public string getState () {return state;} public void action () {system.out.println ("this 1 and the state is" state);}}
Package pattern.c.mediator;
public class ConMediator implements Mediator {private ConColleague1 con1; private ConColleague2 con2; public void setCon1 (ConColleague1 con1) {this.con1 = con1;} public void setCon2 (ConColleague2 con2) {this.con2 = con2;} public void changeCol1 () { String state = con1.getState (); con2.setState (state); con2.action ();} public void change (); con1.setState; con1.ction (); con1.action () }}
Package pattern.c.mediator;
Public interface mediator {void setcon1 (contolleague1 con2); void setcol1 (); void changecol2 ();} package pattern.c.mediator;
public class MediatorTest {public static void main (String [] args) {Mediator mediator = new ConMediator (); ConColleague1 col1 = new ConColleague1 (mediator); col1.setState ( "lq test in the MediatorTest main 18"); ConColleague2 col2 = New concolleague2 (Mediator); Mediator.SetCon1 (col1); Mediator.SetCon2 (col2); col1.change ();}}
*********************************************************** ********************
// Iterator mode example
Package pattern.c.itrator;
Interface aggregate {myiterator itrator ();
Class conalygate {public myiterator itrator () {return new contitector ();}}
Interface myiterator {Object first (); object low (); boolean hasnext (); object next ();}
class ConMyIterator implements MyIterator {Object [] objs = new Object [100]; int index = 0; public Object First () {index = 0; return objs [index];} public Object Last () {index = objs.length - 1; Return Objs [index];} public boolean Hasnext () {Return Index Public class iteratorpattern { Public static void main (string [] args) {}} *********************************************************** ******************** // Template Method mode example Package Pattern.c.Template_Method; Abstract Class Father {Abstract Void Med0 (); Abstract Void Med1 (); // Operation is a template method public void Operation () {Med0 (); Med1 (); // and other logic}} class child extends Father} class child@ Void Med0 () {System.out.Println ("THE Med0 Method");} public void med1 () {system.out.println ("the med1 method");}} Public class templateMethodPattern { Public static void main (string [] args) {}} *********************************************************** ******************** // CHAIN OF RESPONSIBLITY mode // Requests the request on the chain // If it is a request for the current node, the request // of the request // of each node is passed to achieve a chain structure Package Pattern.c.chain_of_responsiblity; Interface Handler {Void Handlerequest (int key);} class ConHandler1 implements Handler {private Handler handler; public ConHandler1 (Handler handler) {this.handler = handler;} public void handleRequest (int key) {if (key == 1) {System.out.println ( "handle in 1" ); // Handle Something} else {handler.handlerequest (key);}}} class ConHandler2 implements Handler {private Handler handler; public ConHandler2 (Handler handler) {this.handler = handler;} public void handleRequest (int key) {if (key == 2) {System.out.println ( "handle in 2" ); // Handle Something} else {handler.handlerequest (key);}}} class ConHandler3 implements Handler {private Handler handler; public ConHandler3 (Handler handler) {this.handler = handler;} public void handleRequest (int key) {if (key == 3) {System.out.println ( "handle in 3" ); // Handle Something} else {handler.handlerequest (key);}}} public class ChainOfResponsiblityPattern {public static void main (String [] args) {Handler handler = new ConHandler2 (new ConHandler1 (new ConHandler3 (null))); handler.handleRequest (3);}} ********* *********************************************************** ************ // Interpreter mode example / * * Variable indicates that the variable is stored in the context * Constant end express expression * AND and relationships Double-purpose * Not reverse relationship Package pattern.c.interpreter; Import java.util. *; class Context {private Map variables = new HashMap (); public boolean lookUp (Variable name) {Boolean value = (Boolean) variables.get (name); if (value == null) {return false;} return value.booleanValue ( ); Public void bind (variable name, boolean value) {variables.put (name, new boolean (value);}} Interface Expression {Boolean Interpret (CONTEXT CONT); Class Constant Implements Expression {Private Boolean Value; Public Constant (Boolean Value) {this.Value = Value;} PUBLIC Boolean Interpret (CONTEXT CONT) {Return Value;}} Class Variable Implements Expression {Private String Name; Public Variable (String Name) {this.name = name;} public boolean interface {return cont.lookup (this);}} class And implements Expression {private Expression left; private Expression right; public And (Expression left, Expression right) {this.left = left; this.right = right;} public boolean interpret (Context cont) {return left.interpret (cont ) && right.Interpret (cont);}} class Not implements Expression {private Expression expression; public Not (Expression expression) {this.expression = expression;} public boolean interpret (Context cont) {return expression.interpret (cont);!}} public class InterpreterPattern {public static void main (String [] args) {Context Cont = New Context (); variable variable = new variable ("parameter1"); contResses and = new and (new not (new not (new connection) New and (new constant (false), new variable ("parameter1"))))))); // (!) && ((false) &.interpret (cont);}} *********************************************************** ******************** // MEMENTO mode example Package pattern.c.memento; Class Memento {String Value1; Int Value2; Public Memento (String Value1, Int Value2) {this.Value1 = Value1; this.Value2 = Value2;}} class Originator {private String value1; private int value2; public Originator (String value1, int value2) {this.value1 = value1; this.value2 = value2;} public void setMemento (Memento memento) {value1 = memento.value1; value2 = memento.value2;} public Memento createMemento () {Memento memento = new Memento (value1, value2); return memento;} public void setValue1 (String value1) {this.value1 = value1;} public void setValue2 (int value2) {this .value2 = value2;}} class CareTaker {private Memento memento; public Memento retrieveMemento () {return memento;} public void saveMemento (Memento memento) {this.memento = memento;}} public class MementoPattern {public static void main (String [] args) {Originator originator = New Originator ("Test1", 1); Caretaker Caretaker = New Caretaker (); // Save Status Caretaker.SaveMemento (Originator.SetValue1 ("Test2"); Originator.SetValue2 (2); // Restore status originator.setMemento (Caretaker.RetrieveMemento ());}} *********************************************************** ********************