美文网首页
设计模式

设计模式

作者: feiyingmm | 来源:发表于2018-03-20 22:17 被阅读0次

    单例模式

    1、配置文件读取类,协调系统整体行为
    2、创建一个对象消耗资源过多
    public class Singleton {
         private static Singleton singleton = null; 
         //限制产生多个对象
         private Singleton(){
         }  
         //通过该方法获得实例对象
         public static synchronized Singleton getSingleton(){
                 if(singleton == null){
                        singleton = new Singleton();
                 }
                 return singleton;
         }
    }
    

    模板方法模式

    工厂模式

    代理模式

    • 静态代理
    public Interface IUserDao{
       public void eat();
    }
    public class UserDaoImpl implements IUserDao{
      public void eat(){
        //业务逻辑
      }
    }
    public class UserDaoProxy implements IUserDao{
      private IUserDao userDao;
      public UserDaoProxy(IUserDao userDao){
        this.userDao = userDao;
      }
      public void eat(){
        //修饰
        userDao.eat();
      }
    }
    main(){
      IUserDao userDao = new UserDaoProxy(new UserDaoImpl);
      userDao.eat();
    }
    
    • JDK动态代理
    class MyHandler implements InvocationHandler{
      private Object target;
      public MyHandler(Object obj){
        this.target = obj;
      }
      public Object invoke(Object proxy, Method method, Object[] args){
        //加逻辑
        Object result = method.invoke(target, args);
      }
    }
    Interface IUserDao{
      void eat();
    }
    class UserDaoImpl implements IUserDao{
      void eat(){
        //业务逻辑
      }
    }
    main(){
      IUserDao userDao = new UserDaoImpl();
      MyHandler myHandler = new MyHandler(userDao);
      IUserDao userDao = Proxy.newProxyInstance(classloader, userDao.getClass().getInterfaces(), myHandler);
      userDao.eat();
    }
    

    相关文章

      网友评论

          本文标题:设计模式

          本文链接:https://www.haomeiwen.com/subject/msjiqftx.html