Java Design Pattern Demo example

Source: Internet
Author: User

Create a pattern

1. Factory methods Mode (Factory method) The program creates an action object that alone walks out of the process and creates a product factory interface. The actual work is transferred to the detailed subclass. The flexibility of system expansion is greatly improved, and the abstraction of interface provides the best abstraction mode for interdependent object creation.

2. Abstract Factory is a case of multiple product grades, while the factory approach model is for a single product grade.

Import java.awt.*;import javax.swing.*;import java.awt.event.*;p ublic class Testabstractfactory {public static void Main (string[] args) {guifactory fact=new swingfactory (); Frame F=fact.getframe (); Component C1=fact.getbutton (); Component C2=fact.gettextfield (); f.setsize (500,300); F.setlayout (new FlowLayout ()); F.add (C1); F.add (C2); F.setvisible (True); F.addwindowlistener (new Windowadapter () {public void windowclosing (WindowEvent e) {system.exit (0) ;}});}} Abstract class Guifactory{public abstract Component Getbutton ();p ublic abstract Component Gettextfield ();p ublic Abstract Frame getframe ();} Class Awtfactory extends Guifactory{public Component Getbutton () {return new button ("AWT button"); Public Frame GetFrame () {return new frame ("AWT frame");} Public Component Gettextfield () {return new TextField (20);}} Class Swingfactory extends Guifactory{public Component Getbutton () {return new JButton ("Swing button");} Public Frame GetFrame () {return new JFrame ("Swing frame");} Public Component Gettextfield () {REturn New JTextField (20);}}  
3. The singleton mode (Singleton) improves the conflicts between global variables and namespaces. Can be said to be an improved global variable. Such a class has only one instance, and provides a way to access the global point, more flexibly guaranteeing the creation of instances and interview constraints. There is only one instance in the system, so the construction method should be private a hungry man: Create a static instance directly when the class loads lazy: Create an instance only when you need it for the first time. Then Newinstance method to add synchronous a hungry man-style than lazy, although the resource utilization is poor.

But don't sync.

4. The construction mode (builder) cuts the interior representation and construction of an object, and a construction process can create objects of different appearances. Can be simplified to a template method mode.

5. Prototype mode (PROTOTYPE) creates a new object (clone) from a prototype object.

In Java to give the implementation of the Clonable interface, the detailed class to implement this interface, and give the Clone () method Implementation details, this is the application of simple prototype mode.

? Shallow copy: Simply copy the value of the simple attribute and the address of the object property? Deep copy: The object referenced by this object is copied, and there is a possibility of circular referencing. Capable of solving deep copies with serialization. Written into the stream and read it again, this will be the result of a deep copy of the object.

Import java.io.*;p Ublic class Testclonealbe {public static void main (string[] args) throws Exception {Father f=new Father ( ); User U1=new User ("123456", f); User u2= (user) U1.clone (); System.out.println (U1==U2); System.out.println (U1.F==U2.F);}} Class User implements cloneable,serializable{string password; Father f;public User (String password,father f) {this.password=password;this.f=f;} Public Object Clone () throws Clonenotsupportedexception {//return super.clone (); ObjectOutputStream Out=null;o Bjectinputstream in=null;try {bytearrayoutputstream bo=new bytearrayoutputstream (); out = new ObjectOutputStream (bo); O Ut.writeobject (this); Out.flush (); byte[] Bs=bo.tobytearray (); Bytearrayinputstream bi=new Bytearrayinputstream (BS); in = new ObjectInputStream (BI); Object o=in.readobject (); return o ;} catch (IOException e) {e.printstacktrace (); return null;} catch (ClassNotFoundException e) {e.printstacktrace (); return null;} Finally{try {out.close (); In.close ();} catch (IOException e) {e.printstacktrace ();}}}} ClassFather implements serializable{} 

How a structural model assembles a simple class into a large system based on a certain type of structure

6. Adapter mode (Adapter) when the original type does not make any changes, an adapter class is used to turn an interface into an interface, which expands the new interface. Flexible and versatile to fit all old customs. The idea of breaking stereotypes and adapting to a new pattern is the essence of object-oriented. The adapter mode of the class implemented by inheriting way and the adapter mode of the object which is realized by the aggregation are different, each take the director.

7. The combination mode (Composite) describes the relationship of the whole and the local in a tree-like structure, which makes the client treat the whole object and the local object equally.

import java.util.*;p ublic class Testcomposite {public static void main (string[] args) { Node n1=new Leafnode (3); Node n2=new Leafnode (4); Node n3=new Leafnode (6); Node n4=new Leafnode (5); Node n5=new Leafnode (2); Node n6=new Leafnode (9); Node n7=new Leafnode (12); Node n8=new Leafnode (7); Node n9=new Leafnode (8); Node c1=new Compositenode (N1,N2,N3); Node c4=new Compositenode (N8,N9); Node c3=new Compositenode (N5,C4); Node c2=new Compositenode (N4,C3); Node c5=new Compositenode (N6,N7); Node root=new Compositenode (C1,C2,C5); System.out.println (Root.getvalue ());}} Abstract class Node{public abstract int GetValue ();} Class Leafnode extends Node{int value;public leafnode (int value) {This.value=value;} public int GetValue () {return value;}} Class Compositenode extends Node{private List children=new ArrayList ();p ublic compositenode (node ... nodes) {for (node N: nodes) {children.add (n);}} public int getValue () {int result=0;for (Node n:children) {result+=n.getvalue ();} return result;}} 

8. Decorative mode (Decorator) expands the functionality of the object in a way that is transparent to the customer. The user chooses the component which composes the object according to the function demand, realizes by the method chain call.

The ability to add functionality dynamically to objects is more flexible than inheritance.

9. Proxy mode uses a proxy object as a proxy for another object, which is transparent to the customer. There is an abstract subject class. Both the detail topic class and the Proxy topic class inherit (implement) the abstract topic, and the methods in the proxy topic class invoke the corresponding method in the detailed topic class.

10. The state of the Flyweight pattern object is divided into intrinsic state and outer state.

The intrinsic state does not change with the environment, so it can be shared by the system.

11. Façade mode (facade) when visiting the subsystem, visit through a façade object. The facade class is a singleton. The customer code only needs to communicate with the façade object, does not need to communicate with the object inside the detailed subsystem, causes the coupling relationship between them to weaken.

This time the presentation layer and the logical layer are isolated, encapsulating the underlying complex processing. Provide users with a simple interface, this sample is everywhere.

The façade mode is often more of a system architecture design. In my project, I realized the interface of the façade mode and provided the best solution for the decoupling of the complex system.

12. Bridging mode (bridge) Decouples abstraction and implementation. So that they can change individually. So that an inheritance relationship does not bear the two variables. A composition is used instead of an embodiment of inheritance.

Behavioral Patterns describe how to divide responsibilities between objects

13. The policy model (strategy), like the LayoutManager and detailed layout manager relationships, defines methods in the abstract policy class, encapsulates the easily changing portions as interfaces, and typically strategy encapsulate some algorithms to make them interchangeable. Bruce Zhang mentions in his blog that the strategy model is actually an "interface-oriented" programming approach. That's the proper. Implemented in the detailed policy subclass. Customer code according to different needs to choose the corresponding detailed class, such as e-commerce in a variety of price algorithms. Once a strategy is selected, the entire system execution period is unchanged.

14. Template method prepares an abstract class. Define the partially defined logic in some methods and use other abstract methods to implement the remaining logic. Different subclasses have different implementations of these logic. How to use: Define multiple abstractions, define and implement a template method, and place the steps in this detailed method. Deferred to child class implementation. Subclasses can change the mutable parts of a parent class, but cannot change the top-level logic represented by a template method.

15. The Observer pattern (Observer) defines a one-to-many dependency between objects, and when an object's state changes, all objects that depend on it are notified and actively updated by themselves. The separation between the observer and the observed person. Provides a clear boundary for module partitioning.

Coordination between low-coupling objects is completed.

The event model in Java is an application.

16. The iterator pattern (Iterator) is similar to the Iterator in the collection, using iterators to unify the traversal of different collection objects.

In most systems, arrays, sets, lists, and queues are used, and it is necessary to care about the context of iterative patterns. In the traversal algorithm. The iterative pattern provides a sequential access container for traversal, GOF gives a way to access the individual elements of a container (container) object without exposing the object's internal details.

. NET is the use of iterators to create a collection for foreach.

public class Testiterator {public static void main (string[] args) {stack s=new stack (); S.push ("Liucy"); S.push ("Huxz"); S.push ("George"); LinkedList l=new LinkedList () l.addfirst ("Liucy"), L.addfirst ("Huxz"), L.addfirst ("George");p rint (L.iterator ());} public static void print (Itr it) {while (It.hasnext ()) {System.out.println (It.next ())}}} Interface Itr{boolean Hasnext (); Object next ();} Class stack{object[] os=new object[10];int index=0;private void expand () {object[] os2=new object[os.length*2]; System.arraycopy (os,0,os2,0,os.length); os=os2;} public void push (Object o) {if (index==os.length) expand (); os[index]=o;index++;} Public Object pop () {index--;object o=os[index];os[index]=null;return o;} Private class Stackitr implements Itr{int Cursor=0;public Boolean hasnext () {return cursor}public Object next () {return os[ cursor++];}} Public Itr iterator () {return new Stackitr ();}} Class Linkedlist{private class Node{object o; Node Next;public node (Object o) {this.o=o;} public void Setnext (Node next) {This.next=next;}Public Node GetNext () {return this.next;}} Node head;public void AddFirst (Object o) {node n=new node (o); N.setnext (head); head=n;} Public Object Removefirst () {Node n=head;head=head.getnext (); return N.O;} Class Linkedlistitr implements Itr{node Currentnode=head;public Boolean hasnext () {return this.currentnode!=null;} Public Object Next () {Node n=currentnode;currentnode=currentnode.getnext (); return n.o;}}  Public Itr iterator () {return new Linkedlistitr ();}}

17. Chain of responsibility (Chain of Responsibility) multiple processor objects are attached to a string. Requests are passed on this chain. Handled by the processor that processed the request. The client making the request does not know which object is processing the request.

public class Testchain {public static void main (string[] args) {String pass1= "123456"; String pass2= "123456"; String personid= "123456789012345678"; String email= "[email protected]"; register (pass1,pass2,personid,email);} public static void Register (String pass1,string pass2,string personid,string email) {Filter f1=new PasswordFilter1 (); Filter f2=new PasswordFilter2 (); Filter f3=new Personidfilter (); Filter f4=new emailfilter (); F1.setnext (F2); F2.setnext (F3); F3.setnext (F4); System.out.println (F1.dofilter (Pass1,pass2,personid,email));}} Abstract class Filter{filter Next=null;public Filter GetNext () {return next;} public void Setnext (Filter next) {This.next = next;} public string DoFilter (string pass1,string pass2,string personid,string email) {if (Next==null) return "success"; else return NE Xt.dofilter (Pass1,pass2,personid,email);}} Class PasswordFilter1 extends Filter{public string doFilter (string pass1,string pass2,string personid,string email) {if ( ! (Pass1.equals (PASS2))) Return "two times password input inconsistency"; elseReturn Super.dofilter (Pass1,pass2,personid,email);}} Class PasswordFilter2 extends Filter{public string doFilter (string pass1,string pass2,string personid,string email) {if ( Pass1.length ()!=6) return "Password length must be 6"; else return Super.dofilter (Pass1,pass2,personid,email);}} Class Personidfilter extends Filter{public string doFilter (string pass1,string pass2,string personid,string email) {if ( Personid.length ()!=15 && personid.length ()!=18) return "ID card number is illegal"; else return Super.dofilter (Pass1,pass2, Personid,email);}} Class Emailfilter extends Filter{public string doFilter (string pass1,string pass2,string personid,string email) {int i1= Email.indexof ("@"); int I2=email.indexof ("."); if (i1==-1 | | i2==-1 | | i2-i1<=1 | | i1==0 | | i2==email.length ()-1) return "email illegal"; else return Super.dofilter (Pass1,pas  S2,personid,email);}}

18. Status mode (state) changes its behavior when the object's internal state changes. Encapsulates the behavior of the object being studied in a different state object.

19. Memo Mode (Memento) The memo object is used to store a snapshot object with an object, saving its internal state so that it can be resumed at any time.

Memo role: Saves the internal state of the initiator object and protects the content from objects other than the initiator object. Narrow interface: The interface that the owner object and other objects see, simply agreeing to pass the memo object to another object.

Wide interface: the interface that the initiator can see. Agree to read the internal state. Initiator role: Create and use a Memo object to save its status owner role: Responsible for saving the memo object. White Box Implementation: The Memo class is also visible to other classes so that the initiator's state may have security issues. Black box Implementation: The memo class as the initiator of the internal class, external to provide an identity interface.

public class Testmemento{public static void Main (string[] args) {originator ori=new originator (); Caretaker C=new Caretaker () ori.setstate ("State 1"), Ifmemento M=ori.creatememento (); C.save (m); Ori.setstate ("State 2 "); M=c.retrieve (); Ori.restore (m); SYSTEM.OUT.PRINTLN ("Now State:" +ori.getstate ());}} Class originator{string state;public void SetState (String s) {state=s; SYSTEM.OUT.PRINTLN ("State Change to:" +s);} Public String GetState () {return this.state;} Public Ifmemento Creatememento () {Return to New Memento (state);} public void Restore (Ifmemento m) {Memento mt= (Memento) m;this.state=mt.getstate (); Private class Memento implements Ifmemento{private string State;public Memento (string s) {this.state=s;} Public String GetState () {return this.state;}}} Class Caretaker{private Ifmemento m;public Ifmemento Retrieve () {return this.m;} public void Save (Ifmemento m) {this.m=m;}} Interface ifmemento{}

Java Design Pattern Demo example

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.