Single mode and factory mode

Design pattern 1.Singleton mode The singleton pattern ensures that there is only one instance of a class, which can no...
Design pattern

Design pattern

1.Singleton mode

The singleton pattern ensures that there is only one instance of a class, which can not be obtained directly through the new object.
Single case mode (starved Han mode):

/** * @author xiaobai */ public class Singleton { static Singleton instance=new Singleton();//Defining a unique instance object of a class private Singleton(){ }//Will construct private, can not get instance object directly through new public static Singleton getInstance()//Get instance object { return instance; } }

Get the instance object of the class through: Singleton singleton=Singleton.getInstance();
The instance created by starved Chinese mode when the class is loaded is thread safe.
2. Singleton mode (lazy mode)

/** * @author xiaobai */ public class Singleton { static Singleton instance=null;//Initial reference to null private Singleton() { }//Will construct private, can not get instance object directly through new public Singleton getInstance() { if(instance==null) { instance=new Singleton(); } return instance; }//Get instance object }

Thread safety problem: lazy mode is an instance created when it is first used. Thread is not safe.
In order to ensure thread safety, we need to add synchronized code blocks and variable modification by volatile.

public class Singleton { static volatile Singleton instance=null;//Initial reference to null private Singleton() { } public Singleton getInstance() { if(instance==null) { synchronized(Singleton.class) { if(instance==null) { instance=new Singleton();//Check whether the instance is null twice to avoid being instantiated twice. } } } return instance; } }

Application scenario:
The task manager and recycle bin of windows are single application
2. The configuration of web files is also a single example. All objects share one configuration file
3. The connection pool design of database is also a single example, which can improve the efficiency of opening and closing database
4. The design of thread pool is also a single example, saving the creation and destruction of threads

Summary: in the case of resource sharing, the single instance mode can save unnecessary resource loss and control resources
Convenient communication of resources.

Advantages and disadvantages:
advantage:
1 because there is only one instance in the class, memory cost and system performance loss can be saved.
2. Multiple occupation of resources can be avoided
3. Ensure that other objects are the same when they are accessed
Disadvantages:
1. There is no abstraction layer, so the scalability is poor
To some extent, it violates the principle of "single responsibility"
Abuse of single instance will bring some negative problems. For example, in order to save resources, designing database connection pool object as single instance mode may lead to connection pool overflow due to too many programs sharing connection pool object.

2. Simple factory mode

Define a factory class. It can return different instances according to different parameters. The created instances usually have the same parent class

Simple plant structure:
Factory: it is responsible for implementing the internal logic of creating all instances. The method of creating product class of factory class can be directly called by the outside world to create the required product object.
Product: the factory class creates the parent class of the object and declares the common abstract method, which is responsible for describing the common interface shared by all instances.
Concrete Product: concrete implementation class. All objects created are instances of a specific class.

Abstract class parent:

public abstract class Product { //Parent of all objects public abstract void use(); }

Specific implementation class:

public class OldProduct extends Product { @Override public void use() { System.out.println("old product use"); } }
public class NewProduct extends Product{ @Override public void use() { System.out.println("new product use"); } }

Factory class:

public class ProductFactory { public Product create(String type) { Product product=null; switch (type) { case "old": product=new OldProduct(); break; case "new": product=new NewProduct(); break; default:break; } return product; }//Different object instances are produced by different input parameters. }

Application scenario of simple factory pattern: factory class creates fewer objects.

Advantages and disadvantages:
advantage:
1. The client does not need to know the class name of the specific product class created, but only the corresponding parameters of the specific product class
The simple factory pattern realizes the division of responsibility by this way. It provides a special factory class for creating objects
Disadvantages:
1. Violating the opening and closing principle, the responsibility of a factory is too heavy
2. It is difficult to expand the system. Once a new product is added, the factory logic has to be modified

3. Abstract factory mode

Abstract Factory Pattern is to create other factories around one super factory
Interface

//Define an interface named bean, which has a method eat public interface Beans { public void eat(); }
//Define an interface called flour, which has a method sweet public interface Flour { public void sweet(); }

The following are the specific implementation classes:

//Tofo class implements beans interface and eat method public class Tofu implements Beans { @Override public void eat() { System.out.println("tofu can eat"); } }
//Tempeh class implements beans interface and eat method public class Tempeh implements Beans { @Override public void eat() { System.out.println("tempeh can eat"); } }
//The bun class implements the flour interface and the sweet method public class Bun implements Flour { @Override public void sweet() { System.out.println("bun is sweet"); } }
//The noodles class implements the flour interface and the sweet method public class Noodles implements Flour { @Override public void sweet() { System.out.println("noodles is sweet"); } }

To create an abstract factory:

public abstract class AbstractFactory { public abstract Beans getBeans(String beans); public abstract Flour getFlour(String flour); }

Specific factory:

public class BeansFactory extends AbstractFactory{ @Override public Beans getBeans(String beans) { switch (beans) { case "Tofu": return new Tofu(); case "Tempeh": return new Tempeh(); default:break; } return null; } @Override public Flour getFlour(String flour) { return null; } }
public class FlourFactory extends AbstractFactory { @Override public Beans getBeans(String beans) { return null; } @Override public Flour getFlour(String flour) { switch (flour) { case "Bun": return new Bun(); case "Noodles": return new Noodles(); default:break; } return null; } }

Test results:

public class Test { public static void main(String[] args) { AbstractFactory af1=new BeansFactory(); AbstractFactory af2=new FlourFactory(); Beans beans=af1.getBeans("Tofu"); beans.eat(); Flour flour=af2.getFlour("Bun"); flour.sweet(); } }

Operation results

tofu can eat bun is sweet

Application scenario of abstract factory mode:
Abstract factory pattern can be used when the objects to be created are a series of interrelated or interdependent product families.
1 QQ for skin, a complete set of replacement.
2 generate programs from different operating systems.

Advantages and disadvantages:
advantage:
When multiple objects of a product family are to be used, it can be ensured that they are all in the same product family. If you want to expand, you only need to add factory class and product class to the same product family
2. Isolate the generation of specific classes, with good encapsulation
Disadvantages:
It is not easy to expand product family. When expanding new products, the interface of abstract factory needs to be modified

4 factory method mode

Define a factory interface for creating product objects, and postpone the actual creation of product objects to specific sub factory classes

The factory method pattern includes the following four roles: Product, concrete Product, factory, and concrete factory
Compared with the simple factory pattern, the creation of the simple factory pattern class depends on the factory class, which results in the modification of the factory class when extending. Factory method pattern creation creates a factory interface and multiple factory implementation classes. When you want to extend, add the corresponding factory classes.

Factory interface:

//Define the main interface machine and its method produce public interface Machine { public Flour produce(); }

Factory implementation class:

//The machine that defines the production package implements the factory interface and the method produce public class BunMachine implements Machine { @Override public Flour produce() { return new Bun(); } } //The machine that defines the noodle production implements the factory interface and the method produce public class NoodlesMachine implements Machine { @Override public Flour produce() { return new Noodles(); } }

Product interface:

public interface Flour { public void sweet(); }

Specific products:

//The definition class bun (package) implements the interface flow (flour) public class Bun implements Flour { @Override public void sweet() { System.out.println("bun is sweet"); } public Bun() { System.out.println("Bun is created"); } } //The defining class Noodles implements the interface flour public class Noodles implements Flour { @Override public void sweet() { System.out.println("noodles is sweet"); } public Noodles() { System.out.println("Noodles is created"); } }

Test:

public class Test { public static void main(String[] args) { Machine machine=new BunMachine(); Flour flour=machine.produce(); flour.sweet(); Machine machine1=new NoodlesMachine(); Flour flour1=machine1.produce(); flour1.sweet(); } }

Operation result:

Bun is created bun is sweet Noodles is created noodles is sweet

Application scenario of factory method mode:
1 the client does not know the specific class created
2 implementation of subclass method by concrete factory class

Advantages and disadvantages:
advantage:
Users only need to know which factories to create, not care about the details of creation, and do not need the implementation of specific classes
2. All concrete factory classes implement the same interface, which is called polymorphic factory pattern;
3 in line with the opening and closing principle, only factory class and specific products need to be added for new products, without code modification, with good scalability
Disadvantages:
Considering the scalability of the system, the introduction of the abstraction layer increases the abstraction and understanding difficulty of the system.

Comparison of three modes:

Simple factory mode There is only one factory, which produces different product instances through the input parameters Abstract factory pattern There are multiple factories, each factory can produce multiple products, and different factory instances can produce different products Factory method mode There are multiple factories. Each factory only produces one product. Different factory instances can produce different products

Reference article:
https://www.cnblogs.com/pjl1119/p/9715458.html
https://www.jianshu.com/p/67ede26212be

20 June 2020, 01:22 | Views: 3768

Add new comment

For adding a comment, please log in
or create account

0 comments