设计模式

Posted on 2018-03-09 18:04  小小蜗牛灬  阅读(102)  评论(0编辑  收藏  举报

一. 发布者 订阅者模式   观察者模式;

二.代理模式:代理对象,目标对象,代理对象中保存目标对象的引用,通过操作代理对象而间接操作目标对象。好处:不改变目标对象的基础上扩展目标对象的操作,坏处:产生多余的代理类;

      https://www.cnblogs.com/cenyu/p/6289209.html

      静态代理:

      动态代理模式:http://rejoy.iteye.com/blog/1627405     不创建代理对象 利用 jdk中的 Proxy.newProxyInstance(类加载器,目标对象实现的接口,invocationHandler ) 和invocationHandler 进行创建代理对象;invocationHandler 进行目标对象的方法调动

      (反射),https://www.cnblogs.com/cenyu/p/6289209.html

      Cglib代理:安卓不支持;

三.抽象工厂、简单工厂:简单工厂,只有一个工厂,构建产出不同的产品;抽象工厂可以构建出多个抽象工厂的实现,进而可以构建出多个工厂里的多个产品;

四。构建者模式 Builder模式;

五。策略模式    http://blog.csdn.net/u012124438/article/details/70039943

六。单例模式

  1):饿汉式

   优缺点:以空间换时间,线程安全,使用效率高,但是单例在未使用的时候就被初始化了 占了内存空间;

public class Singleton {
    private static final Singleton INSTANCE=new Singleton();
    private Singleton(){}
    public static Singleton getInstance(){
        return INSTANCE;
    }
}

 2):懒汉式

  以时间换空间,线程不安全 需要 加锁解决线程同步问题

public class Singleton{  
      private static Singleton instance = null;  
      private Singleton(){}  
      public static Singleton newInstance(){  
          if(null == instance){  
              instance = new Singleton();  
          }  
          return instance;  
      }  
  } 

枷锁后的:

 public class Singleton {
      private static Singleton instance;
      private Singleton(){
      }
      public static synchronized Singleton getInstance(){
          if(instance == null){
              instance = new Singleton();
          }
          return instance;
      }
  }

添加了锁,会使运行时间增加效率低了。进一步优化:双层验证机制 ,第一个验证是为了避免不必要的锁。缺点 第一次加载效率低 因为走了锁

 public class Singleton {
      private static Singleton instance;
      private Singleton(){}
      public static Singleton getInstance(){
          if(instance == null){
              synchronized (Singleton.class){
                  if(instance == null){
                      instance = new Singleton();
                  }
              }
          }
          return instance;
      }
  }

 

 

3)。静态内部类方式:延迟加载 有保证 线程安全

  

 public class Singleton {
      private static Singleton instance;
      private Singleton() {
      }
      public static class SingletonInstance {
          private static final Singleton INSTANCE = new Singleton();
      }
      public static Singleton getInstance() {
          return SingletonInstance.INSTANCE;
      }
  }

 

  

 

 

 

 

  

Copyright © 2024 小小蜗牛灬
Powered by .NET 8.0 on Kubernetes