Java Common Design Patterns

Source: Internet
Author: User

Classification of design Patterns

In general, design patterns fall into three broad categories:

Create five types of models: Factory method mode, abstract Factory mode, singleton mode, builder mode, prototype mode.

Structure mode, a total of seven kinds: Adapter mode, adorner mode, proxy mode, appearance mode, bridging mode, combined mode, enjoy the meta-mode.

There are 11 types of behavioral Patterns: Strategy mode, template method mode, observer mode, iteration sub-mode, responsibility chain mode, Command mode, Memo mode, state mode, visitor mode, mediator mode, interpreter mode.

First, single-row mode:

The so-called single-column design pattern simply says that no matter how the program works, a class with a single-column design pattern (the Singleton Class) will always have only one instanced object generated. The specific implementation steps are as follows:

(1) The construction method of a class with a single-column design pattern privatization (private modification)

(2) The instantiated object of the class is generated within it and encapsulated into the private static type.

(3) Defines a static method that returns an instance of the class.

1. A Hungry man type (thread safe, low efficiency)

/**   *   * Single-instance mode implementation: A Hungry man, thread  -safe but inefficient * * Public class  singletontest {          Private singletontest () {      }         privatestaticfinalnew  Singletontest ();           Public Static singletontest getinstancei () {          return  instance;      }     
View Code

2. Full Han style (non-thread safe)

/*** Single-mode implementation: full-Chinese, non-thread-safe **/  Public classSingletontest {Privatesingletontest () {}Private StaticSingletontest instance;  Public Staticsingletontest getinstance () {if(Instance = =NULL) Instance=Newsingletontest (); returninstance; }  } 
View Code

3, thread safety, but very low efficiency

/*** thread safe, but very inefficient * **/  Public classSingletontest {Privatesingletontest () {}Private StaticSingletontest instance;  Public Static synchronizedsingletontest getinstance () {if(Instance = =NULL) Instance=Newsingletontest (); returninstance; }  } 
View Code

4, thread-safe, and high efficiency

/*** thread safety and high efficiency **/  Public classSingletontest {Private StaticSingletontest instance; Privatesingletontest () {} Public Staticsingletontest getistance () {if(Instance = =NULL) {              synchronized(Singletontest.class) {                  if(Instance = =NULL) {instance=Newsingletontest (); }              }          }          returninstance; }  } 
View Code

Second, the factory model

The program adds a transition between the interface and the subclass, through which the sub-class instantiation object that implements the common interface can be dynamically obtained.

InterfaceAnimal {//define an animal's interface     Public voidSay ();//How to speak}     classCatImplementsAnimal {//define a subclass cat@Override Public voidSay () {//overwrite Say () methodSystem.out.println ("I'm a cat, Meow! "); }  }     classDogImplementsAnimal {//Define Subclass Dog@Override Public voidSay () {//overwrite Say () methodSystem.out.println ("I'm a puppy, bark! "); }  }     classFactory {//Defining Factory Classes     Public StaticAnimal getinstance (String className) {Animal a=NULL;//Defining Interface Objects        if("Cat". Equals (ClassName)) {//determine which child is the tag of the classA =NewCat ();//instantiating interfaces through cat subclasses        }          if("Dog". Equals (ClassName)) {//determine which child is the tag of the classA =NewDog ();//instantiating interfaces through the dog subclass        }          returnA; }  }      Public classFactorydemo { Public Static voidMain (string[] args) {Animal a=NULL;//Defining Interface ObjectsA = Factory.getinstance (Args[0]);//obtaining instances through the factory        if(A! =NULL) {//determines whether an object is emptyA.say ();//Calling Methods        }      }  } 
View Code

Three, Agent mode

Refers to the operation of a real topic by an agent theme, the real topic to perform specific business operations, and the subject of the agent responsible for other related business processing. For example, in life, through the proxy access to the network, the customer through the Network Proxy link network (specific business), the proxy server to complete user rights and access restrictions and other Internet-related operations (related business).

InterfaceNetwork {//defining the network interface     Public voidbrowse ();//define the abstract method of browsing}     classRealImplementsNetwork {//real-World Internet Operation     Public voidbrowse () {//Overwrite abstract methodsSYSTEM.OUT.PRINTLN ("Browse the internet! "); }  }     classProxyImplementsNetwork {//Agent Online    PrivateNetwork Network;  PublicProxy (Network Network) {//set the actual operation of the agent         This. Network = network;//set the subclass of the proxy    }          Public voidCheck () {//Authentication ActionsSystem.out.println ("Check if the user is legal! "); }          Public voidbrowse () { This. check ();//invoking a specific proxy business operation         This. Network.browse ();//invoke the real internet operation    }  }      Public classProxydemo { Public Static voidMain (String args[]) {Network net=NULL;//Defining Interface ObjectsNET =NewProxy (NewReal ());//instantiate the agent while the actual operation of the incoming agentNet.browse ();//Invoke agent's internet operation    }  } 
View Code

Iv. Observer Mode (50773358):

The observer pattern, also known as the Publish-subscribe mode (publish/subsribe) mode, belongs to the behavior pattern. It defines a one-to-many relationship that allows multiple observer objects to listen to a Subject object at the same time, and when the subject object changes, it notifies all observer objects so that they can automatically update themselves.

For example: The public number, the user is the observer, the public number is the observer, there are many users concerned about the programmer of the public number, when the public number updates will notify these subscribers.

Abstract Observer (Observer):

It defines an Update method:

Abstract Observer (Observer)

An updated method is defined inside:

public interface Observer {    public void update(String message);}

Specific Observer (Concrereobserver)

The user is the observer, which implements the updated method:

public class WeixinUser implements Observer { // 用户名 private String name; public WeixinUser(String name) { this.name = name; } @Override public void update(String message) { System.out.println(name + "-" + message); }}

Abstract Observer (Subject)

Abstract topic, provides three methods of attach, Detach, notify:

public interface Subject {    /** * 增加订阅者 * @param observer */ public void attach(Observer observer); /** * 删除订阅者 * @param observer */ public void detach(Observer observer); /** * 通知订阅者更新消息 */ public void notify(String message);}

Specific observed (ConcreteSubject)

The public number is a specific subject (a specific observer), which stores users subscribing to the public number and implements the methods in the abstract theme:

PublicClassSubscriptionsubjectImplementsSubject { //store subscription to the public number of the user private list<observer> weixinuserlist = new arraylist<observer> (); c4> @Override public void Attach (Observer Observer) {weixinuserlist.add (Observer);} @Override public void Detach (Observer Observer) {weixinuserlist.remove (Observer);} @Override public void Notify (String message) {for (Observer observer:weixinuserlist) {observe R.update (message); } }}

Client Calls
Publicclass Client { public static void main (string[] args) {Subscriptionsubject msubscriptionsubject=
          
           new Subscriptionsubject (); 
           //create user Weixinuser user1=new Weixinuser ("Yolanda Maple"); Weixinuser user2=New Weixinuser ("The Brow of the Moon"); Weixinuser user3=New Weixinuser ("Purple Xuan"); //Subscribe to public number Msubscriptionsubject.attach (user1), Msubscriptionsubject.attach (User2); Msubscriptionsubject.attach ( USER3); //Public number update sends a message to subscribers of the subscription msubscriptionsubject.notify ("Liu Wangshu's Column updated");}}        
          

Results

杨影枫-刘望舒的专栏更新了月眉儿-刘望舒的专栏更新了紫轩-刘望舒的专栏更新了

Java Common Design Patterns

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.