Java Common 10 Design Patterns Sample Induction | Have been packed please take

Source: Internet
Author: User

Design patterns are a set of reusable, most known, categorized purposes, code design experience Summary.

GitHub Address
Designpattern

Article description
A demo, a collection of 10 commonly used design patterns, each model using easy to accept the case of the story, according to the pattern of subcontracting, using design patterns before and after comparison, interface display definition explained, so that you have a deeper understanding of each design pattern.
Most of the cases come from Zhang Hongyang's blog. If there is any mistake, please contact me to remove the infringement.

Project structure

Package structure. png
The design pattern is divided into three types, a total of 23 kinds:
Create pattern: Singleton mode, abstract Factory mode, builder mode, Factory mode, prototype mode.
Structural mode: Adapter mode, bridge mode, decoration mode, combination mode, appearance mode, enjoy meta mode, proxy mode.
Behavioral Patterns: Template method mode, command mode, iterator mode, observer pattern, Mediator mode, Memo mode, interpreter mode, state mode, policy mode, responsibility chain mode (responsibility chain mode), visitor mode.
Above link Click Jump directly to github corresponding mode resolution within

Mainactivity.png
Blog Directory
1. Design pattern Observer pattern (Observer pattern) take public service as an example
2. Design mode Factory mode (Factory pattern) Start with the meat-selling bun.
3. Design Pattern Singleton design pattern (Singleton pattern) Full Parse
4. Design pattern Policy mode (strategy pattern) with role play as background
5. Design mode adapter mode (Adapter pattern) with mobile phone charger as an example
6. Design mode command Pattern Management smart Appliances
7. Design pattern Decorator mode (Decorator pattern) brings you back to the legendary world
8. Design pattern appearance mode (facade pattern) One-click Movie mode
9. Design pattern Template Method mode (Templatemethod pattern) show Programmer's Day
10. Design mode status mode (state pattern) as an example of a vending machine
The package in which the corresponding pattern resides
1. Observer
2. Factory
3. Singleton
4. Strategy
5. Adapter
6. Command
7. Decorator
8. Façade
9. Template Method
10. State
Pattern Analysis

    1. Observer pattern
      Defines a one-to-many dependency between objects, so that when an object changes, all its dependents are notified and updated automatically.

There are many places in the JDK or andorid that implement the observer pattern, such as xxxview.addxxxlistenter, of course. Xxxview.setonxxxlistener is not necessarily the observer pattern, because the observer pattern is a one-to-many relationship, and for Setxxxlistener is a 1-to-1 relationship, it should be called a callback.

Thematic interface: Subject.java;

/**

    • Register an Observer
      */
      public void Registerobserver (Observer Observer);
      /**
      • Removing an observer
        */
        public void Removeobserver (Observer Observer);
        /**
      • Notify all observers
        */
        public void notifyobservers ();
        Implementation class for service number: Objectfor3d.java

@Override
public void Registerobserver (Observer Observer) {br/>observers.add (Observer);
}
@Override

int index = OBSERVERS.INDEXOF (Observer);
if (index >= 0) {br/>observers.remove (index);
}
}
@Override

for (Observer observer:observers) {
Observer.update (msg);
}
}
/**

    • Topic Update Information
      */
      public void Setmsg (String msg) {
      this.msg = msg;
      Notifyobservers ();
      }
      All observers need to implement this interface: Observer.java

Public ObserverUser1 (Subject Subject) {br/>subject.registerobserver (this);
}
@Override

LOG.E ("-----ObserverUser1", "Get 3D Number:" + msg + ", I want to write it down. ");
}
Last Test: Observeractivity.java

Create a service number
Objectfor3d = new Objectfor3d ();
Create two Subscribers
ObserverUser1 = new ObserverUser1 (Objectfor3d);
ObserverUser2 = new ObserverUser2 (Objectfor3d);
Two observers, send two messages
Objectfor3d.setmsg ("201610121 3D: 127");
Objectfor3d.setmsg ("20161022 3D: 000");

    1. Factory mode
      Simply list the family of this pattern:

1. Static Factory mode

This is the most common, auxiliary class in the project, Textutil.isempty, etc., class + static method.
2. Simple Factory mode (buy meat bun in store)

Definition: By specifically defining a class to be responsible for creating instances of other classes, the instances that are created typically have a common parent class.
Create a meat bun directly from the type: Simpleroujiamofactory.java

Public Roujiamo Creatroujiamo (String type) {
Roujiamo Roujiamo = null;
Switch (type) {
Case "Suan":
Roujiamo = new Zsuanroujiamo ();
Break
Case "La":
Roujiamo = new Zlaroujiamo ();
Break
Case "Tian":
Roujiamo = new Ztianroujiamo ();
Break
default://The default is sour meat pinch bun
Roujiamo = new Zsuanroujiamo ();
Break
}
return Roujiamo;
}
3, factory method mode (open branch)

Definition: Defines an interface to create an object, but subclasses decide which class to instantiate. The factory method model defers the process of instantiating a class to subclasses.
Contrast definition:

1. Defines an interface for creating objects: Public abstract Roujiamo Sellroujiamo (String type);
2, subclasses decide to instantiate the class, you can see our bun is a subclass generated.
Offer to create meat Bun Shop Abstract method: Roujiamostore.java
Public abstract Roujiamo Sellroujiamo (String type);
Concrete implementation of abstract methods: Xianroujiamostore.java
The store still uses the Simple Factory mode: Xiansimpleroujiamofactory.java
4. Abstract Factory mode (using the raw materials provided by the official)

Definition: Provides an interface for creating a family of related or dependent objects without explicitly specifying a specific class.
Contrast definition:
1, provide an interface: public interface Roujiamoylfactroy
2, for the creation of related or dependent objects of the family public Meat createmeat ();p ublic Yuanliao Createyuanliao (); Our interface is used to create a series of raw materials.
Create an interface factory for supplying raw materials: Roujiamoylfactory.java
The respective branch implements the interface, completes the raw material to provide: Xianroujiamoylfoctory.java
When preparing, use the official ingredients: Roujiamo.java

/**

    • Preparatory work
      */
      public void Prepare (Roujiamoylfactory roujiamoylfactory) {
      Meet Meet = Roujiamoylfactory.creatmeet ();
      Yuanliao Yuanliao = Roujiamoylfactory.creatyuanliao ();
      LOG.E ("---roujiamo:", "using the official ingredients---" + name + ": kneading-cleavers-Completing the preparation Yuanliao:" +meet+ "Yuanliao:" +yuanliao ");
      }
      1. Single Case design mode
        The singleton mode is designed to avoid wasting resources by creating multiple instances, and multiple instances are prone to errors due to multiple calls, while using singleton mode ensures that there is only one instance in the entire application.

Definition: Only three steps are required to ensure the uniqueness of the object
(1) Do not allow other programs to use the new object
(2) Creating objects in this class
(3) Provide a way for other programs to get the object
Contrast definition:
(1) Privatization of the constructor for this class
(2) Create a class object in this class with new
(3) Define a public method that returns the object created in the class
A hungry man type [available]:singletonehan.java
]:singletonlanhan.java with lazy type [double check lock recommended

Private Singletonlanhan () {}
private static Singletonlanhan Singletonlanhanfour;
public static Singletonlanhan Getsingletonlanhanfour () {
if (Singletonlanhanfour = = null) {
Synchronized (Singletonlanhan.class) {
if (Singletonlanhanfour = = null) {
Singletonlanhanfour = new Singletonlanhan ();
}
}
}
return singletonlanhanfour;
}
Internal class [Recommended with]:singletonin.java

enumeration [Recommended]:singletonenum.java

Single-instance design mode. png

    1. Policy mode
      Policy mode: The algorithm family is defined, encapsulated separately, so that they can be replaced by each other, this pattern allows the algorithm to change independently of the customer using the algorithm.

To create a game role as an example:
Parent of the original game role: Role.java
After the discovery of duplicate code, the reconstructed parent class: Role.java
Summarize:
1. Package changes (package the code that may change).
2, multi-use combination, less with inheritance (we use a combination of methods, set up the algorithm for the customer)
3, for the interface programming, not for the implementation (for role class design completely for roles, and the implementation of the skill is not related)
Final Test: Create a role:

Rolea Rolea = new Rolea ("---A");
Rolea.setidisplaybehavior (New Displayyz ())
. Setiattackbehavior (New ATTACKXL ())
. Setidefendbehavior (New Defendtms ())
. Setirunbehavior (New RUNJCTQ ());
Rolea.display ();//Appearance
Rolea.attack ();//xxx
Rolea.run ();//Escape
Rolea.defend ();//Defense

    1. Adapter mode
      Definition: The interface of a class is transformed into another interface that the customer expects, and the adapter allows classes that are incompatible with the original interface to work together. This definition is good, saying that the function of the adapter is to turn an interface into another interface.

To the charger as an example: mobile phone chargers are generally around 5V bar, our celestial household AC voltage 220V, so the mobile phone charging requires an adapter (buck)
A mobile phone: Mobile.java
The phone relies on an interface that provides a 5 V voltage: V5power.java
We have a 220V household AC: V220power.java
Adapter, complete 220V to 5V effect: V5poweradapter.java
Final Test: Make a phone call:

Mobile mobile = new mobile ();
V5power v5power = new V5poweradapter (new V200power ());
Mobile.inputpower (V5power);

    1. Command mode
      Definition: Encapsulates a request into an object so that different requests, queues, or logs can be used to parameterize other objects. The command mode also supports the revocable operation. (Simplification: Encapsulates a request into an object, decoupling the action requestor from the action performer.) )

Demand: Recently smart home appliances are very hot, assuming now have TV, computer, electric lights and other home appliances, now you need to do a remote control of all household appliances switch, require each button corresponding function for the user personalization, for the new buy home appliances to have a very strong expansion.
1, the API:Door.java of home appliances
2. Encapsulate the command into a class:
Unified Command Interface: Command.java
Appliance implements this interface: Dooropencommand.java
3, REMOTE control: Controlpanel.java
4, define a command, can do a series of things: Quickcommand.java

Quickcommand Quickclosecommand = new Quickcommand (new Command[]{new Lightoffcommand (light), New Computeroffcommand ( Computer), new Doorclosecommand (Door)});
Controlpanel.setcommands (6, Quickopencommand);
Controlpanel.keypressed (6);
5, Remote Control Panel execution: Commandactivity.java

Controlpanel.setcommands (0, New Dooropencommand (door));//Open Door
controlpanel.keypressed (0);

Command mode

    1. Decorator mode
      Decorator mode: To extend functionality, decorators provide a more resilient alternative to integration, dynamically attaching responsibility to objects.

A simple description of where the decorator pattern works, when we have designed a class, we need to add some auxiliary functionality to this class, and do not want to change the code of this class, this is when the decorator mode Xiong Wei. There is also a principle: classes should be open to extensions and closed to modifications.

Requirements: Design Game equipment system, the basic requirements, to be able to calculate each kind of equipment in the mosaic of various gems after the XXX Force and Description:

1, Equipment of super class: Iequip.java
2, the realization of each equipment class:
Eg: Weapon implementation class: Armequip.java
3, the decoration of the super-class (decoration also belongs to equipment): Iequipdecorator.java
4, the decoration of the realization class:

Eg: Sapphire implementation Class (additive): Bluegemdecorator.java
5. Final Test: Calculate XXX Force and view Description:

LOG.E ("---", "one set of 2 rubies, 1 sapphire boots:");
Iequip Iequip = new Redgemdecotator (new Redgemdecotator (New Bluegemdecotator ()));
LOG.E ("---", "xxx Force:" + iequip.caculateattack ());
LOG.E ("---", "description:" + iequip.description ());

    1. Appearance mode
      Definition: Provide a unified interface to access a group of interfaces in the subsystem, the appearance defines a high-level interface, making the subsystem easier to use. In fact, in order to facilitate the use of customers, a group of operations, packaged into a method.

Requirements: I prefer to watch movies, so I bought a projector, computer, stereo, design the room's lights, bought a popcorn machine, and then I want to see the movie, I need a key to watch and a key to close.
Switch operations for each device class:
Eg: Popcorn machine: Popcornpopper.java
Cinema class: Hometheaterfacade.java

/**

    • One click to view the shadow
      */
      public void Watchmovie () {
      Computer.on ();
      Light.down ();
      Popcornpopper.on ();
      Popcornpopper.makepopcorn ();
      Projector.on ();
      Projector.open ();
      Player.on ();
      Player.make3dlistener ();
      }
      Final Test: One click to view the shadow:

New Hometheaterfacade (computer, light, player, Popcornpopper, projector). Watchmovie ();

    1. Template method Mode
      Definition: The skeleton of an algorithm is defined, and some steps are deferred to subclasses, and the template method allows subclasses to redefine the steps of the algorithm without changing the structure of the algorithm.

Requirements: A brief description: The company has a program ape, test, HR, project manager and other people, the following use template method mode, record all the staff's work situation
Three types of roles in template method patterns
1. Specific methods (concrete method)
2. Abstract method
3. Hook method
Worker's Super class: Worker.java

Specific methods
Public final void Workoneday () {
LOG.E ("Workoneday", "-----------------work Start----------------");
Entercompany ();
Work ();
Exitcompany ();
LOG.E ("Workoneday", "-----------------work End----------------");
}
Working abstract methods
public abstract void work ();
Hook method
public Boolean isneedprintdate () {
return false;
}
private void Exitcompany () {
if (Isneedprintdate ()) {
LOG.E ("Exitcompany", "---" + new Date (). toLocaleString () + "--->");
}
LOG.E ("Exitcompany", name + "---leave the Company");
}
Programmer implementation Class (Time to learn): Itworker.java

/**

    • Override this method of the parent class so that you can see the time that leaves the company br/>*/
      @Override

      return true;
      }
      Final Test:

See how all the people work:

Qaworker qaworker = new Qaworker ("Tester");
Qaworker ();
Hrworker hrworker = new Hrworker ("Lily elder sister");
Hrworker.workoneday ();
...
View program Ape leaves the company time:

Itworker itworker = new Itworker ("Jingbin");
Itworker.workoneday ();

    1. State mode
      Definition: Allows an object to change its behavior when the internal state changes, and the object looks as if it has modified its class.

The definition begins to blur again, and when the internal state of the object changes, its behavior changes as the state changes, and it looks as if a similar one has been reinitialized.

Requirements: Has a vending machine as an example (there is a coin, no coin, such as the status and coin, coin, etc.)

Initial implementation of the vending machine to be improved: Vendingmachine.java
Improved vending machine (more malleable): Vendingmachinebetter.java

Put the money
public void Insertmoney () {
Currentstate.insertmoney ();
}
Refund
public void Backmoney () {
Currentstate.backmoney ();
}
Turning Crank
public void Turncrank () {
Currentstate.turncrank ();
if (CurrentState = = Soldstate | | currentstate = = winnerstate) {
Currentstate.dispense ();//Two cases will be shipped
}
}
Out Products
public void dispense () {
LOG.E ("Vendingmachinebetter", "---issue of a commodity");
if (Count > 0) {
count--;
}
}
Set the corresponding state
public void SetState (state state) {
This.currentstate = State;
}
interface of the state: State.java

The interface implementation class for the corresponding state:
Eg: Winning status: Winnerstate.java
Eg: Sales Status: Soldstate.java
Improved Vending machine testing:

Initialize the vending machine with 3 items in it
Vendingmachinebetter machinebetter = new Vendingmachinebetter (3);
Machinebetter.insertmoney ();
Machinebetter.turncrank ();
Reference links
http://blog.csdn.net/lmj623565791/article/category/2206597
Thanks

Java Common 10 Design Patterns Sample Induction | Have been packed please take

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.