Create Design Patterns

Source: Internet
Author: User

What do you mean, patterns

The model describes a representative repetition problem and its solution. This type of problem can be repeated in different forms, allowing users to extrapolate and apply to different environments.

The features that the pattern contains:

1. Mode Name

2, the problem that the mode can solve

3. Solutions

4. Effect after using this mode (pros and cons)

Why do you want to learn design patterns?

Patterns are summed up from experience, and proven schemes, patterns can only become patterns after multiple validations in the actual system.

1) Promote reuse and improve the reusability of the system.

2) Improve the maintainability of the system, through the use of design patterns, when the system is facing the upgrade and maintenance, the maintenance costs will be controlled at the lowest level.

3) Increase the expression ability: The design pattern has the very strong language expression. Design pattern is a summary of the solution, so that design patterns can better communicate and communicate, become a common language between developers, so that more developers to use, in turn, promote the development of design patterns and applications.

4) Help us to design the software better.

Pattern classification

Schema mode: Architecture refers to the organizational structure of a software system as a whole. Architectural patterns describe some of the rules and guidelines for the organizational structure of software systems. Through these rules and guidelines, we can effectively organize predefined, well-defined subsystems.

Design pattern: A design pattern describes a core solution that is constantly being reproduced in a part of a software system, which appears in a well-developed design structure and can be applied to similar environments that arise in the future. Compared to the architecture model, the design pattern focuses on the more microscopic issues.

Classification of design Patterns

Basic design Pattern (Gof) (23): not associated with a specific domain, platform, or programming language

According to the purpose, that is, what this design pattern is doing is classified as:

1) Create pattern: involves the creation of objects

Singleton mode, Factory mode, builder mode, prototype mode

2) Structural pattern: involves a combination of classes and objects

Facade appearance mode, proxy mode, adapter mode, decorative mode

3) Behavioral patterns: Describe the way in which classes and objects are exchanged and assigned responsibilities. The main goal is decoupling

Observer mode, command mode, template mode

Factory mode Factory

Definition: Factory mode is the centralized creation of instance objects

Benefits of using the factory model:

1) separate the customer class from the factory class. Consumers need a product at any time, just request it from the factory. Consumers can accept new products without modification

2) The creation of objects is done by the factory, and the coupling between classes is greatly reduced, becoming a coupling between the class and the factory.

3) object creation and use of separation, to achieve the purpose of decoupling.

Support for object-oriented design principles:

1) The Simple Factory mode must support the opening and closing principle, but the principle of closure is not enough. (To modify the factory class when introducing new products)

2) The factory method mode can satisfy the opening and shutting principle

3) in order to meet the dependency inversion principle often requires the use of Factory mode

factory-Simple Factory mode (static Factory)

public class factory{

public static Sample creator (int which) {

GetClass Generation sample You can typically use dynamic classes to load a load class.

if (which==1)

return new Samplea ();

else if (which==2) return new Sampleb ();

}

}//sample Samplea=factory.creator (1);

Does not involve the specific subclass of sample, achieves the encapsulation effect, also reduces the opportunity of the error modification

Factory-Factory Method mode

There are several roles to be aware of using factory methods

First you want to define the product interface, such as the above sample, the product interface under the sample interface implementation class, such as Samplea,

The second is to have a factory class that is used to generate the product sample

Interface ifactory{

Sample createproduct ();

}

Class Afactory implements ifactory{

Sample createproduct () {

return new Samplea ();

}

The creation of the object is delegated to the subclass to implement, and the subclass implements the factory method to create the object. Of course, it is possible to implement a series of specific products in subclasses. Subclass to decide which specific product to instantiate.

Factory-Factory Method mode

Manufacturing Plant of Product B

Class Bfactory implements ifactory{

Sample createproduct () {

return new Sampleb ();

}

It is also possible to generate different specific products in the Createproduct () method based on specific context calculations or configuration file information;

Test:

Ifactory factory = new Bfactory ();

Sample Product = Factory.createproduct ();

factory-Abstract Factory

Public abstract class factory{

Public abstract Sample creator ();

Public abstract Sample2 Creator (String name);

}

public class Simplefactory extends factory{

Public Sample Creator () {

.........

return new Samplea

}

Public Sample2 Creator (String name) {

.........

return new SAMPLE2A

}

}

public class Bombfactory extends factory{

Public Sample Creator () {

......

return new Sampleb

}

Public Sample2 Creator (String name) {

......

return new SAMPLE2B

}

}

Multiple product families, together with multiple factory methods, form the abstract factory model.

Single case Mode singleton

The main role is to ensure that only one instance of a class is present in a Java application.

such as creating a directory, the database connection requires such a single-threaded operation

The advantage is that memory can be saved because it limits the number of instances and facilitates Java garbage collection (when used with data sharing)

Using the singleton mode Singleton (1) (A Hungry Man type) (preloaded)

public class Singleton {

Construction method is private

Private Singleton () {}

Define yourself an instance within yourself, note that this is private

Pre-load

private static Singleton instance = new Singleton ();

This provides a static method for external access to this class.

Direct access to

public static Singleton getinstance () {

return instance;

}

}

Using a singleton mode singleton (2) (Lazy-loading)

public class Singleton {

Lazy load private static Singleton instance = NULL;

public static synchronized Singleton getinstance () {

This method is better than the above, and does not have to be generated every time.

Object, only the first time when the instance is generated, improve the efficiency!

if (instance==null)

Instance=new Singleton ();

return instance;

}

}

This way, in the case of multi-threaded, because each time the instance is acquired to lock the getinstance () method to obtain a lock to run, the efficiency will be affected.

Using a singleton mode singleton (3)

Double lock Mechanism:

public class Singleton {

private static Singleton instance = NULL;

public static Singleton getinstance () {

if (instance==null)

--1 synchronized (singleton.class) {

---2 if (instance = = null) {

---3 instance = new Singleton ();

}

}

return instance;

}

}

This method only adds a sync lock when initializing the singleton part of the code, which improves efficiency.

Prototype Mode-prototype

Definition: Specifies the kind of object created with the prototype instance, and creates a new object by copying the prototypes. Allow one object to create another customizable object without knowing the details of how to create it at all

Implementation method:

By passing a prototype object to the object to be created, the object to be created will be created by requesting the prototype object to copy themselves.

Use case:

1) Many times, when creating objects, only some attribute values are different, and most are similar, the user of the class is how to create the object of the class, the internal structure of the class is not concerned about the situation, but the initialization of such objects is relatively complex, and takes a long time or resources, In this case, we can consider using the prototype mode.

Prototype mode-prototype (Shallow clone) (the base data type is cloned)

public class Abstractspoon implements cloneable{

String Spoonname;

public void Setspoonname (String spoonname) {

This.spoonname = Spoonname;

}

Public String Getspoonname () {

return this.spoonname;

}

Public Object Clone () {

Object object = null;

try {

Object = Super.clone ();

} catch (Clonenotsupportedexception exception) {

System.err.println ("Abstractspoon is not cloneable");

}

return object; or return (Object) Super.clone ();

}

}

Prototype mode-prototype (Deep clone) (the reference data type is cloned)

Public Mans Deepclone () {

try {

Bytearrayoutputstream bo = new Bytearrayoutputstream ();

ObjectOutputStream outobj = new ObjectOutputStream (bo);

Outobj.writeobject (this);

Bytearrayinputstream bi = new Bytearrayinputstream (Bo.tobytearray ());

ObjectInputStream outin = new ObjectInputStream (BI);

Mans m = (man) outin.readobject (); return m;

} catch (Exception e) {

E.printstacktrace ();

}

return null;

}

design mode-builder (Builder mode)-Create pattern

Used to create a complex object step by step

The builder mode is to separate the process of creating complex objects from the creation of components, respectively, by using the builder class and the Director class to achieve the purpose of decoupling.

Applies to the following situations:

1) When creating complex objects, the algorithm should be independent of the parts of the object and how they are assembled.

2) When the construction process must allow the constructed object to have different representations.

Note: The builder model emphasizes the process of having the same build sequence, and the specifics of the construction are different. The build order between the internal builds of the complex objects created is usually stable, but the construction of the objects inside the object often faces complex changes.

Design mode-builder-Create mode

First, an interface is required to represent a stable sequential construction process. List the parts that this object needs to be created.

Public interface Builder {

Creating a part A such as creating a car wheel

void Buildparta ();

Creating a part B such as creating a car steering wheel

void Buildpartb ();

Creating a part C such as creating a car engine

void Buildpartc ();

Returns the final assembly of the finished product (back to the last assembled car)

The assembly process for the finished product is not carried out here, but instead is transferred to the following Director class.

Thus realizing the understanding of the coupling process and components

Product GetResult ();

}

The concrete implementation of the builder is actually built in different cars, wheels, steering wheel, engine construction process is different of course different car.

Design mode-builder-Create mode

Use the Director to control the construction process and isolate the connection between the user and the construction process.

public class Director {

Private builder Builder;

The user tells the conductor what kind of car I need, and the different builder means the car needs to be different.

Public Director (Builder builder) {

This.builder = Builder;

}

Parta a part PartB PARTC the final composition of a complex object

This is the process of assembling the wheel steering wheel and the engine into a car.

public void construct () {

Builder.buildparta ();

BUILDER.BUILDPARTB ();

BUILDER.BUILDPARTC ();

}

}

Design mode-builder-Create mode

The concrete implementation of builder ConcreteBuilder:

To build or assemble parts of the product by completing the interface builder specifically;

public class ConcreteBuilder implements Builder {

Part Parta, PartB, PARTC;

public void Buildparta () {

Here's how to build Parta code specifically

}

public void Buildpartb () {

Here's how to build PARTB code specifically

}

public void Buildpartc () {

Here's how to build PARTC code specifically

}

Public Product GetResult () {

Return to final assembly of finished product results

}

}

Use Builder mode-Create pattern

Specific construction of the component

ConcreteBuilder builder = new ConcreteBuilder ();

Different build processes, such as order ...

Director Director = new Director (builder);

Start building

Director.construct ();

Get the final product

Product Product = Builder.getresult ();

Create 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.