Simple implementation of java design patterns (1) - Create schema

Reference article:

  1. Overall: https: //www.cnblogs.com/adamjwh/p/9033545.html
  2. Singleton: https: //www.cnblogs.com/ygj0930/p/10845530.html

Create a schema divided into the following.
Singleton (the Singleton) mode: simultaneous multi-threaded to ensure access to an object and method, only one instance of the operation
prototype (the Prototype) mode: an object as a prototype, by its replication and cloning of a plurality of similar and prototype the new instance.
Factory method (FactoryMethod) mode: the definition of a factory interface used to create the product, the subclass producedOneproduct.
Abstract Factory (AbstractFactory) mode: create a product family of interfaces, each subclass can produceA series ofRelated products.
Builder (Builder) mode: a complex objectInto a plurality of portions of relatively simpleAnd then create them according to the different needs of each, and finally to construct the complex objects.

A, singleton

  • Definitions : Singleton pattern ensures that only one instance of a class, and to instantiate the instance to provide the entire system. In a computer system, thread pool, cache, log object, the dialog box, the printer, the graphics driver objects are often designed in one embodiment

  • Features :
    1): Only one instance of
    2): You must create their own unique instance of
    3): This example must be provided to all other objects
    4):In addition to construction method, the other is static

1. lazy man (at the time of the first call instantiation own)

public class Singleton{
	//将构造函数设置为私有,避免类在外部实例化
	private Singleton(){}
	//设置为静态,这样就可以每一次调用都是同一个对象
	private static Singleton single=null;
	public static Singleton getInstance(){
		//只有在没有实例的情况下才创建实例,保证只有一个实例
		if(single==null){
			single=new Singleton();
		}
		return single;
	} 
}

Singleton defined by the constructor of the class is instantiated avoids externally, a virtual machine within the same range, the only instance can only be accessed Singleton getInstance () method is private.

(In fact, through the Java reflection mechanism can instantiate a class constructor is private, it causes substantially all of the fail-Java single embodiment. This problem is not discussed here, deceiving tentatively believe that the absence of reflection .)

But to achieve the above example of lazy single thread does not consider security issues, it is not thread-safe, concurrent instances Singleton environment is more likely to achieve thread-safe, there are three ways, are the transformation of this method getInstance to ensure that the lazy man's singleton thread-safe, if you first contact singleton, thread safety is not very understanding, you can skip the next three strips, see a hungry man single cases, such as watching behind go back to consider thread safety issues.

  1. Synchronization method applied in getInstance
public static synchronized Singleton getInstance(){
	if(single == null){
		single=new Singleton();
	}
	return single;
}
  1. Double-checked locking

A. Note that the two judgments null is a great sense of

  1. The first is to make a null object every time he created only when it is locked
  2. The second is to prevent the judgment null when two threads access the method, into the first empty judgment method, an entry, a blockage, when the first thread releases the lock after creating the instance, also entered the second lock, also created situations instance.

II. In the instance of an object over there need to add the volatile keyword

  1. Here volatile if not an error may occur, i.e., when the code reading is determined to statement on line 11,If the instance is not null, but the object instance referenced may not have finished initializing, The thread will have access to the object has not been initialized. The reason is because the first 14 lines of code to create an object, this code can be decomposed into three lines of pseudo-code, i.e. allocate memory object, initialize the object, the memory address just assigned points instance, are referred to as 1,2 3, between 2 and 3 may be reordered reordering after initialization becomes the final step. Therefore, intra-thread semantics thread A (all threads must comply with intra-thread semantics when executing a Java program, it will not change the program to ensure that reordering the results in the single-threaded) has not changed, but the reordering of the A2 and A3 cause the thread B is judged that instance is not empty, the next thread to access the object instance B referenced case, thread B will have access to the object has not been initialized. The delay can be achieved using a volatile initialization thread-safe,When nature is prohibited by reordering between 2 and 3, to ensure the safety of lazy initialization thread
public class Singleton {

    private volatile static Singleton instance;
    private static Object syncRoot = new Object();
    
    private Singleton() {
    }

    public static Singleton getInstance() {
        //双重锁定
        if(instance == null) {
            synchronized (syncRoot) {
                if(instance == null) {
                    instance = new Singleton();
                }
            }
        }
        
        return instance;
    }
    
}

  1. Static inner classes (both realized the thread-safe, but also to avoid the performance impact caused by synchronization.)

The use of class loading to ensure only one instance create instance
Disadvantages: do not delay to create objects created will cause initialization time becomes longer when the class is loaded

public class Singleton {

    //静态内部类
    private static class SingletonHolder {
        public static Singleton instance = new Singleton();
    }
    
    private Singleton() {
    }
    
    public static Singleton getInstance() {
        return SingletonHolder.instance;
    }
    
}

Example 2. starving single (at initialization class is instantiated on their own)

Hungry Chinese-style class at the same time created already created a static object used by the system will no longer change, so inherently thread-safe.

public class Singleton{
	private Singleton(){}
	//定义为final和static,无法修改
	private static final Singleton single = new Singleton().;
	public static Singleton getInstance(){
		return single;
	}
}

Disadvantage of the above four methods achieve a single embodiment of

1. When the embodiment will destroy single deserialized

It will not be called when it is deserialized getXX () method, thus ensuring bypass logicsheets embodiment, the direct generation of a new object, the disruption of a single embodiment.

Solution:

  1. Method override deserialization class method returns the deserialized single embodiment, rather than creating a new object.
public class Singleton implements Serializable{
	//当前实例
	public static Singleton INSTANCE = new Singleton();     
 
//双重锁定部分代码
	。。。

	//重写反序列化,使其直接返回当前实例
	   private Object readResolve() {     
            return INSTANCE;     
      }   
}
  1. Rewrite private constructor
//维护一个volatile的标志变量在第一次创建实例时置为false;重写构造函数,根据标志变量决定是否允许创建。
private static volatile  boolean  flag = true;
private Singleton(){
    if(flag){
    flag = false;   //第一次创建时,改变标志
    }else{
        throw new RuntimeException("The instance  already exists !");
    }

The best method of use - using single-mode enumeration Example

public enum singletonEnum{
	INSTANCE;
	private String name;
	public String getName(){
		return name;
	}
	public void setName(String name){
		this.name=name;
	}
}

the reason

  1. Use SingletonEnum.INSTANCE access, no longer need to define the methods and call the method getInstance
  2. JVM unique enumeration instance, avoiding the reflection and deserialization above-mentioned single embodiment destruction occurs, each of the enumerated type defined enumeration and then the JVM is unique.
    (Enumerated type enumeration object name attribute is output only when the result of the sequence, deserialization time is according to enumerated objects by name lookup valueOf method of java.lang.Enum)
  3. Note: The compiler needs to override the ban enumerated type writeObject, readObject, readObjectNoData, writeReplace readResolve and other methods. )

Prototype mode

  1. Applicable scene:
  • Between the same or similar objects, only a few different individual properties when
  • Create a troublesome object, but convenience copying
  1. Copy the object is not out of the original object, the same property value, but different address object, you can create a large number of similar objects.
  2. Code implements (Cloneable interface implemented using java line)
//具体原型类
class A implements Cloneable{
	//写一个自定的构造方法,方便理解
	A(){
		System.out.println("具体原型创建成功");
	}
	public Object clone throws CloneNotSupportedException{
		System.out.println(“具体原型复制成功”);
		return (A)super.clone();
	}
}
//原型模式的测试类
public class B{
	 public static void main(String[] args)throws CloneNotSupportedException
    {
        A obj1=new A();
        A obj2=(A)obj1.clone();
        System.out.println("obj1==obj2?"+(obj1==obj2));
    }
}
  1. Results are as follows

Specific prototyping success!
Specific prototype replicate success!
obj1 == obj2? false

Factory Pattern

  1. Applicable scene:
  • The other side do not know the specific product name, product name only production plant of clear
  • Create a product generated by the object on a specific plant, abstract factory is only responsible for creating an object interfaces
  • Customers only care about the brand, the product does not care about the details
  1. The general structure
  • Abstract Factory: Provide an interface method for creating an object
  • Concrete Factory: create objects of implementation, different factories to create objects of different products
  • Abstract products: defining product specifications, description of the main characteristics of the product
  • Specific products: implement the abstract product, created by the specific plant, and plant-specific correspondence.
  1. Realization Mode
/**
 *产品类
 **/
//抽象产品
interface product{
    public void show();
}
//具体产品1
class proA implements product{

    @Override
    public void show() {
        System.out.println("A");
    }
}
//具体产品2
class proB implements product{
    @Override
    public void show(){
        System.out.println("B");
    }
}

/**
 *工厂类
 **/
//抽象工厂
interface factory {
    product getPro();
}

//具体工厂1
class facA implements factory{
    @Override
    public product getPro(){
        return new proA();
    }
}

//具体工厂2
class facB implements factory {
    @Override
    public product getPro() {
        return new proB();
    }
}

Abstract factory pattern

  1. Features: When a specific factory not only produce a particular product
  2. Implementation (modify factory class)
    ?????
    interface AbstractFactory
    {
    public newProduct1 the Product1 is ();
    public newProduct2 Product2 is ();
    }

AbstractFactory ConcreteFactory1 the implements class
{
public the Product1 is newProduct1 ()
{
System.out.println ( "DETAILED generating plant 1 -> ... specific product. 11");
return new new ConcreteProduct11 ();
}
public Product2 is newProduct2 ()
{
System.out.println ( "DETAILED generation plant 1 -> ... specific product 21 is");
return new new ConcreteProduct21 ();
}
}
?????

Builder mode

  1. Applicable scene
  • Objects created more complex, there areA plurality of componentsEach member of the complex will vary, the construction of a stable order between the members.
  • Build process and the final product represents independent when
  1. Personal understanding: that the various components of the product realization and segmented construction process and construction to achieve order,When the construction process of a product change, the builders only need to change, and when there is a component of the product relative change, to change the concrete realization of components, each separately, and separates the builder and commander, when construction when the process is changed, only we need to change the commander, while the details of the construction of a process change, need to change only the specific construction methods can builder

  2. The general structure

  • Product role: contains multiple components of complex objects, that is, to achieve the various components
  • Abstract builder: contains abstract methods to create the subdivisions of the product
  • Specific builder: abstract implements the interface builder
  • Commander: Method Invocation builders complete the construction of complex objects

It is similar to the process of the construction of the building, built by the workers, who are directing contractors, construction contractors to complete different parts of the building by each individual schedule, complete the construction of a building

  1. Implementation code
public class Abc {
    public static void main(String[] args) {
        //创建一个建造者
        ture_builder ture_builder=new ture_builder();
        //创建一个指挥者,并且给他建造者
        boss boss=new boss(ture_builder);
        product product=boss.build();
        System.out.println();
    }
}

//产品角色
class product{
    //部分1
    String pat1;
    String pat2;
    public void show(){
        System.out.println("aaa");
    };
}

//抽象建造者
abstract class builder{
    abstract void getpat1();
    abstract void getpat2();
    abstract product getres();
}

//具体建造者
class ture_builder extends builder{
    product pro1=new product();

    @Override
    void getpat1() {
        pro1.pat1="1";
        System.out.println("建造pat1部分");
    }

    @Override
    void getpat2() {
        pro1.pat2="2";
        System.out.println("建造pat2部分");
    }

    @Override
    product getres() {
        return pro1;
    }
}

//指挥者
class boss{
    private ture_builder ture_builder;
    
    boss(ture_builder ture_builder){
        this.ture_builder=ture_builder;
    }
    
    product build(){
        ture_builder.getpat1();
        ture_builder.getpat2();
        return ture_builder.getres();
    }
}
Published 36 original articles · won praise 11 · views 10000 +

Guess you like

Origin blog.csdn.net/s_xchenzejian/article/details/103165193