Offer2-Singleton prove safety mode

topic

Design a class, we can only generate an instance of the class

 

Singleton

Definitions: " a class is only one example , and to instantiate provided to the entire system."

"Ensure that only one instance of a class, and provide a global access point to access it ."

By definition, we can draw in a single embodiment mode, in that regard, we note that:

1. Examples of generated code can only be executed once, in order to ensure a unique instance of the class generated. At the same time the constructor should be set to private, and thus against others create an instance (so if the constructor method of privatization, external calls can not be instantiated class through new, so the first class should be the object instantiation).

2. The definitions and examples of a static static, the instance is created if necessary.

  1) static method can call the same kind of static member, but can not call non-static member directly. Because the static member class is loaded at the time of loading, that had been written before the object is to create a memory.

  2) When you call a non-static member, you need to access by creating objects of that class.

  3) ordinary members of the method (non-static method), you can directly access the non-static and static variables of the same kind.

  4) Static methods belong to the class itself, and only static objects, but not belonging to an object class.

  5) static method can use very frequently when applications can improve system performance.

  6) may be used to define the attributes of the object will not change

3.final keywords. Modification of references, methods and classes

  1) Modified class: This class is final class can not be inherited

  2) modification of the method: the ultimate method can not be overridden by subclasses, but can be inherited

  3) modification of references: must be initialized, and can not be modified. If the reference is a reference data type, the value of the address references can not be modified, but the content of the object inside the reference points may be modified.

4.JVM internal mechanism to ensure that when a class is loaded, the loading process of this class is the thread mutually exclusive.

solution

1. there is a method thread safety issues. If thread A execution to the new method, which is the object has not created, the emergence of a thread B to perform determined sin == null, the condition is true, it will enter into a partially created instance. Two examples of memory will appear.

public class Singleton1{
  private static Singleton1 sin=null;
  private Singleton1()
    {}                  
  public static Singleton1 getSingleton1(){
        if(sin==null){
                sin=new Singleton1();
        }
        return sin;    
    }  
}

 2. In order to solve the above problem, since only one thread at a time to obtain synchronization lock, we can choose to add the synchronized keyword on a method to get the singleton object, but the lock is very time consuming. . It will lead to efficiency too poor, as if the first thread holding the lock, then the lock is released after instantiation, then the second thread will be locked, even after the judge instance has been created, can not be instantiated. That went to the back of the thread concurrency locked here, get every instance, will try to add a synchronization lock.

public class Singleton2{
  private static Singleton2 sin=null;
  private Singleton2()
    {}                  
  public static synchronized Singleton2 getSingleton2(){
        if(sin==null){
                sin=new Singleton2();
        }
        return sin;    
    }  
}

3. To solve this problem, we can not lock on method, and in the internal locking methods. So much better time efficiency.

public  class Singleton3 {
   Private  static Singleton3 SiN = null ;
   Private Singleton3 () 
    {}                   
  public  static Singleton3 getSingleton3 () {
         IF (SiN == null ) {// If the determination is not empty, then that object has been created over, returned directly to the object, it will not come sync locked, do not waste unnecessary resources. Which does not affect the performance of 
            the synchronized (Singleton3. Class ) {
            IF (SiN == null ) {// If a determination is empty, then there will be many threads to create the object through the first layer determination. So even if a thread executing the second layer, releasing the lock, or there will be other thread synchronization lock into this one. To prevent multiple created, so an additional layer of judgment. 
                      SiN = new new Singleton3 ();  
            }
        } 
        }
        return sin;    
    }  
}

 4. not lazy loading, but when the class is created, put the corresponding instance created. But if you need a pass parameters when acquiring an object, you can not use this method & initialized when the class is loaded, the object will be prone to garbage, waste of memory. (Hungry Chinese-style)

public  class Singleton4 { 
// create an object of Singleton4
Private static Singleton4 SiN = new new Singleton4 ();
// constructor to allow private, so that the class is not instantiated
Private Singleton4 () {}
// Get the only available objects
public static Singleton4 getSingleton4 () { return SiN; } }

The static inner class, delay the initialization of the static field use. Use classloader mechanisms to ensure that only one thread at initialization instance. Due SingletonHolder class is not actively used, only by an explicit call getInstance () method, it will explicitly load SingletonHolder class to instantiate INSTANCE.

public class Singleton5{
  private static class SingletonHolder{ 
    private static final Singleton5 INSTANCE=new Singleton5();
 }
  private Singleton5()
    {}                  
  private static final Singleton5 getInstance(){
     return SingletonHolder.INSTANCE;
  }
}

 6. enumeration. Enumerable object is born singleton, clients are not allowed to create an instance of the enumeration class can not be extended. Privatization does not solve the insurance structure, sequence of questions.

public  enum Singleton6 { 
  // create an enumeration object natural single embodiment   INSTANCE;
  // External exposure of the object's interface acquires a   
public Singleton6 the getInstance () {
    return INSTANCE;   } }

 

Extended - design pattern (23 kinds)

1. Design mode according to the intent or purpose of classification, mainly covering three modes Category: Creator / structural / behavioral

2. Creator mode: provide a mechanism to create an object, existing code to increase flexibility and reusability

  1) Factory Method mode : providing a parent class object to create interfaces that allow subclasses decide the type of object is instantiated, the client is not exposed to create a logical object is created.

   2) the abstract factory pattern : to create a series of related objects without specifying their concrete classes. For each variant products, are factory interface to create different classes based on the abstract factory, each plant type can only return to a particular category of products.

  Does not modify the original factory code, can be directly extended, do not care about the details of construction and complex process object instance, and Comparative example process configuration

   3) generator mode: an object configuration codes abstracted from the product category, and in a separate object called the generator.

   4) prototype model: you can replicate an existing object, but the code is not necessary to rely on the class to which they belong. The cloning procedure prototype pattern assigned to the actual object to be cloned, the clone mode all supported object declaration a common interface, the interface is used to clone, without the need to code and the object belongs to the class coupling.

 

   5) singleton

3. The structural model: how to assemble objects into larger class or structure, while maintaining a flexible structure and efficient

   1)适配器模式:使接口不兼容的对象能够互相合作。适配器实现了其中一个对象的接口,并对另一个对象进行封装,适配器接受客户端通过适配器接口发起的调用,并将其转换为适用于被封装服务对象的调用。

   2)桥接模式:可将一个大类或一系列紧密相关的类拆分为抽象和实现两个独立的层次结构,从而在开发时分别使用。

   3)组合模式:将对象组合成树状结构,并且能想使用独立对象一样使用它们。以递归方式处理对象树中的所有项目

   4)装饰模式:允许将对象放入包含行为的特殊封装对象中,来为原对象绑定新的行为。也称为“封装器”,是一个能与其他“目标”对象连接的对象,包含与目标对象相同的一系列方法,它会将所有接收到的请求委派给目标对象。

   5)外观模式:能为程序库、框架或其他复杂类提供一个简单的接口。

  5)代理模式:能够提供对象的代替品或其占位符,代理控制着对原对象的访问,以及允许将请求提交给对象前后进行一些处理。(如windows里面的快捷方式、Spring AOP,即通过在目标类的基础上增加切面逻辑,完成一些和程序业务无关的内容)

  新建一个与原服务对象接口相同的代理类,然后更新应用以将代理对象传递给所有原始对象客户端。代理类接收到客户端请求后会创建实际的服务对象,并将所有工作委派给它。

  6)享元模式:摒弃在每个对象中保存所有数据的方式,通过共享夺各对象所共有的相同状态,从而在有限的内存容量中载入更多对象。

4.行为模式:负责对象间的高效沟通和权责委派

  1)责任链模式:允许将请求沿着处理者链进行发送。收到请求后,每个处理者均可对请求进行处理,或将其传递给链上的下个处理者。

  如jsp servlet中的Filter,Struts2的拦截器

  2)命令模式:将请求转换为一个包含与请求相关的所有信息的独立对象。该转换能根据不同请求将方法参数化、延迟请求执行或将其放入队列中,且能实现可撤销操作。

  3)迭代器模式:在不暴露底层表现形式的情况下遍历集合中所有的元素。

  4)中介者模式:减少对象之间混乱无序的依赖关系。 该模式会限制对象之间的直接交互, 迫使它们通过一个中介者对象进行合作。

  即停止组件之间的直接交流并使其相互独立,这些组件必须调用特殊的中介者对象,通过中介者对象重定向调用行为,以间接的方式进行合作。

  5)备忘录模式:允许在不暴露对象实现细节的情况下保存和恢复对象之前的状态。

  6)观察者模式:定义一种订阅机制, 可在对象事件发生时通知多个 “观察” 该对象的其他对象。

  拥有一些值得关注的状态的对象通常被称为目标, 由于它要将自身的状态改变通知给其他对象, 我们也将其称为发布者,所有希望关注发布者状态变化的其他对象被称为订阅者。

  7)状态模式:能在一个对象的内部状态变化时改变其行为, 使其看上去就像改变了自身所属的类一样。

  8)策略模式:定义一系列算法 并将每种算法分别放入独立的类中 以使算法的对象能够相互替换

  找出负责用许多不同方式完成特定任务的类 然后将其中的算法抽取到一组被称为策略的独立类中

  9)模板方法模式:在超类中定义了一个算法的框架 允许子类在不修改结构的情况下重写算法的特定步骤

  10)访问者模式:将算法与其所作用的对象隔离开。

 该部分图源:https://refactoringguru.cn/design-patterns,侵删~

Guess you like

Origin www.cnblogs.com/lyeeer/p/12180553.html