Spring 常用设计模式

1 篇文章 0 订阅
1 篇文章 0 订阅

目录

 

工厂模式(Factory)

简单工厂

工厂方式模式

抽象工厂

单例模式(Singleton)

懒汉式

饿汉式

注册式

静态内部类

代理模式(Proxy)

静态代理

动态代理

观察者模式(Observer)

策略模式(Strategy)

 模板方法模式(Template Method)

装饰者模式(Decorator)

适配器模式(Adapter)

类适配器

对象适配器

抽象对象适配器


工厂模式(Factory)

工厂模式分为简单工厂,工厂方法模式,抽象工厂模式3种实现方式。工厂模式的目的是为了降低耦合性。将实例化的部分抽离出来。常用于不同的情况下会有不同逻辑。

简单工厂

public interface Factory {     //接口工厂类
   void callPerson();
}
public class Huaewi implemates Factory{   //实现类
     public void callPerson(){
         System.out.println("华为手机打电话");
     }
}
public class Phone implemates Factory{   //实现类
     public void classPerson(){
          System.out.println("苹果手机打电话");
     }
}
public class CallPerson{      //工厂类
     public static Factory StaitccallPerson(String brandName){
         if("huawei".equlas(brandName)){
             return new Huawei();
         }else{
             return new Phone();
}
     }
}
public class staticFactoryClass{  //测试类
     public static void main(String[] args){
         Factory factory=CallPerson.StaticcallPerson("huawei");
         Phone phone=(Phone)CallPerson.StaticcallPerson("phone");
     }
}

简单工厂(StaticFactory)主要是由接口,接口实现类,工厂三个类别组成.
优点:你只需要告诉工厂你要什么,就可以帮你生产出来.

工厂方式模式

public abstract class Factory {     //产品抽象类
   abstract void callPerson();
}
public  class Huaewi extends Factory{   //实现类
     public void callPerson(){
         System.out.println("华为手机打电话");
}
}
public  class Phone extends Factory{   //实现类
     public void callPerson(){
          System.out.println("苹果手机打电话");
     }
}
public  abstract class ProductionFactory{  //工厂抽象类
     abstract Factory createTelePhone();  
}

public class HuaweiFactory extends ProductFactory{
      public Factory createTelePhone(){
          return new Huawei();
      }
}
public class PhoneFactory extends ProductFactory{
      public Factory createTelePhone(){
           return new Phone();
      }
}

public class Test{   //测试类
     public static void main(String[] args){
         ProductFactory product=new HuaweiFactory();
    Factory huawei= product.createTelePhone();
    huawei.callPerson();
     }
}

工厂方法:通过抽象产品类和抽象工厂类.以及对应的具体实现.
抽象产品类的实现为具体的产品生产.抽象工厂类的实现为具体的创建具体的产品

抽象工厂

public abstract class CarFactory {     //产品抽象类
   abstract ITire createTire();  //生产轮胎
   abstract IEngine createEngine(); //生产发动机
   abstarct IBrake  createBranke(); //生产制定系统
}
public interface ITire{  //生产轮胎接口
   void create();
}
public interface IEngine{ //生产轮胎发动机
   void create();
}
public interface IBrake{  //生产制动系统
   void create();
}
public class Tire implemates ITire{  //轮胎实现类
   public void create(){
      System.out.print("生产轮胎")
   }
}

public class Engine implemates IEngine{  //发动机实现类
   public void create(){
      System.out.print("生产发动机")
   }
}

public class Brake implemates IBrake{  //制动系统实现类
   public void create(){
      System.out.print("生产制动系统")
   }
}
public class Q3Car extends CarFactory{  //Q3汽车生产线
    public ITire  createTire(){
      return new Tire();
    }
    public IEngine createEngine(){
       return new Engine();
    }
    public IBrake  createBrake(){
       return new Brake();
    }
}

public class Test{
     public static void main(String[] args){
         CarFactory car=new Q3Car();
car.createTire();
car.createEngine();
car.createBrake();
     }
}


抽象工厂:抽象的产品线,零件的接口类,具体的产品线.具体的零件实现类。就和一条流水线一样。造车子需要轮胎,制动器,发动机.可以有不同的车子和不同的轮胎,制动器,发动机

单例模式(Singleton)

主要是保证实例的独一无二性,提交资源的重复利用。常用于配置读取,IOC容器,监控程序等方面。

懒汉式

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

优点:使用时才初始化
缺点:延迟性,线程不安全

饿汉式

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

优点:线程安全
缺点:一开始就初始化,容易造成垃圾 

注册式

public class Singleton { 
    private Singleton {};
    private static Map<String,Object> map=new ConcurrentHashMap<String,Object>();
    private static object getBean(String beanName){
synchronized(map){
   if(!map.containsKey(beanName)){
       Object obj=null;
       try{
          obj=Class.forName(beanName);
          map.put(beanName,obj);
return obj;
  }catch(classNotFoundExpetion e){
e.printStackTrance();
  }
   }else{
return  obj.get(beanName);
   }
} 
    }
}

优点:适合大量管理单例模式的情况下.
缺点:会有线程不安全问题

静态内部类

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

优点:调用getInstance方式才初始化.并且是静态内部类不会有线程安全问题.比较推荐的一种方式
缺点:延迟初始化 

代理模式(Proxy)

在不改变之前代码的情况下。进行增强操作。代理类主要分为静态代理,动态代理(CGLIB,JDK)。使用的场景主要是日志,事务等功能。

静态代理

public interface Person{  //被代理接口
    void Sing();
}
public class xiaoMing implemates Person{
    public void Sing(){
System.out.pringln("小明唱歌了");
    }
}

public class StaticProxy implemates Person{  //代理类
   private Person person;
   public StaticProxy(Person person){
      this.person=person;
   } 
   public void Sing(){
  	System.out.pringln("唱歌之前");
    person.Sing();
   System.out.pringln("唱歌之后");
   }
}
     public class Test{
        public static void main(String[] args){
            Person person=new xiaoming();
            StaticProxy static=new StaticProxy(person);
            static.Sing();
        }
     }

     静态代理:不改变之前逻辑代码的情况下,进行逻辑增强处理。
     优点:不改变代码逻辑情况下,进行逻辑增强.
     缺点:不可以动态化进行增强

动态代理

Cglib动态代理,底层使用ASM框架对之前的类进行字节码增强处理。动态生成一个代理子类。子类继承对应的父类。重写除了final以外的所有方法。java代码实现是通过实现MethodIntercept

public Class TestProxy{
         public void Test(){
             System.out.println("我是中间执行的方法");
         }
     }
     public Class ProxyImpl implemates MethodIntercept{
        @Overried
   public Object intercept(Object obj,Method method,Object[] params,MethodProxy proxy){
   System.out.println("之前执行");
   proxy.invokerSuper(obj,params);
   System.out.println("之后执行");
   }
     }

JDK动态代理,使用JDK动态代理必须实现接口的方法。java代码的实现是通过实现InvocationHandler

public interface IBrake{
    void create();
  };
  public class Brake implemates IBrake{
public void create(){
   System.out.pringln("创建一个制动系统");
}
  }
  public class ProxyImpl implemates InvocationHandler{
    private Object target;
    public void setTarget(Object target){
          this.target=target
    }
    @Overried
    public Object invoke(Object proxy,Method method,Object[] args) throws T     hrowble{
   System.out.println("之前执行");
   proxy.invoker(target,args);
   System.out.println("之后执行");
       }
  }
  class MethodProxy{
      public Static Object getProxy(Object obj){
      ProxyImpl proxy=new ProxyImpl();
      proxy.setTager(obj);
    Proxy.newProxyInstance(target.getClass().getClassLoad(),target.getClass().Interfaces(),proxy);
      }
  }
  public class Test{
      public static void main(String[] args){
          IBrake brake=new Brake();
          IBrake brakeTest= MethodProxy.getProxy(brake);
          brake.create();
      }
  }

观察者模式(Observer)

定义了对象之间的一对多的关系。当一个对象发生改变时。可以通知到其它对象

public class Subject{       //被观察者
        private List<ObServer> list=new ArrayList<ObServer>();
        public void attach(ObServer obServer){
            list.add(obServer);
        }
        private int state;
        public int getState(){
            return state;
        }
       public int setState(int state){
          this.state=state;
       }
       public void nodifyState(){
         for(int i=0;i<list.size();i++){
           list.get(i).updateState();
         }
       }
  };
   public abstract class ObServer{   //观察者抽象类
    protected Subject subject;
    abstract void updateState();
  }
  public class XiaoMiObServer extends ObServer{  //观察者实现类
     public void updateState(){
        System.out.println("修改了状态");
     }
     public xiaoMiObServer(Subject subject){
        this.subject=subject;
        this.subject.attach(this)
     }
  }
  public class Test{   //测试类
      public static void main(String[] args){
         Subject subject=new Subject();
         XiaoMiObServer xiaomi=new XiaoMiObServer(subject);
         subject.state=10;
      }
  }

策略模式(Strategy)

定义一系列算法,把他们一个个封装起来。并且他们可以相互替换。

public interface Strategy{  //策略接口类
   int doOperation(int num;int num2);
 }
 public class operactionAdd implements Strategy{  //实现类
   public int doOperation(int num;int num2){
      return num+num2;
   }
 }
 public class operactionSub implements Strategy{
   public int doOperation(int num;int num2){
      return num-num2;
   }
 }
 public class operactionMul implements Strategy{
   public int doOperation(int num;int num2){
      return num-num2;
   }
 }
 public class Context{  //策略选择类
    private Strategy strategy;
    public void setStrategy(Strategy strategy){
       this.strategy=strategy;
    }
    public int doOperation(int num;int num2){
        strategy.doOperation(num,num2);
    }
 }
 public class Test{   //测试类
   public static void main(String[] args){
       Context context=new Context();
       context.setStrategy(new operactionAdd());
       context.doOperation(1,2);
       context.setStrategy(new operactionSub());
       context.doOperation(3,1);
       context.setStrategy(new operactionMul());
       context.doOperation(3*1);
   }
 }

 模板方法模式(Template Method)

定义一组算法的骨架,具体的算法实现由子类完成。但不可改变骨架中的结构

public abstrace class Template{  //模板类
    public void TemplateMethod(){ //模板方法
        ParentMethod();
        absMethod1();
        absMethod2();
    }
    public void ParentMethod(){
        System.out.println("父类方法");
    }
    public abstrace void absMethod1();
    public abstrace void absMethod2();
}
public class TemplateImpl extends Template{
    public void absMethod1(){
        System.out.println("子类方法1");
    }
    public void absMethod2(){
        System.out.println("子类方法2")
    }
}
public class Test{
    public static void main(String[] args){
        Template template=new TemplateImpl();
        template.TemplateMethod();
    }
}

装饰者模式(Decorator)

动态的给子类提交一些额外的自职责,比子类更灵活。

public interface Man{
    public void getManDesc();
}
public abstract class AttachedPropertiesDecorator  implements Man{
    private Man man;
    public AttachedPropertiesDecorator (Man man){
        this.man=man;
    }
    public void getManDesc(){
        man.getManDesc();
    }
}
public class NoreMan implements Man{
    public void getManDesc(){
        System.out.pringln("张三");
    }
}
public class CarMan extends AttachedPropertiesDecorator {
    public CarMan(Man man){
        super(man);
    }
    
    public void addCar(){
        System.out.pringln("有车")
    }
    public void getManDesc(){
        super.getManDesc();
        this.addCar();
    }
}
public class HouseMan extends AttachedPropertiesDecorator  {
    public HouseMan(Man man){
        super(man);
    }
    
    public void addHouse(){
        System.out.println(有房);
    }
    
    public void getManDesc(){
        super.getManDesc();
        this.addHouse();
    }
}
public class Test{
    public static void main(String[] args){
        Man noreman=new NoreMan();
        Man carMan=new CarMan(noreman);
        Man houserMan=new HouserMan(carMan);
        houserMan.getManDesc();
    }
}

适配器模式(Adapter)

在不改变之前类的情况下、将这个类转换成另外一个新的类

类适配器

public interface SiginLogin{
    public void login();
}

public class LoginService implements SiginLogin{
    public void login{
        System.out.pringln("普通的登录方法");
    }
}
public interface weiXinInterfaceLogin{
    public void weiXinLogin();
}
public class weiXinLogin extends LoginService implements weiXinInterfaceLogin{
    public void weiXinLogin(){
        login();
    }
}
public class Test{
    public static void main(String[] args){
        weiXinterfaceLogin login=new weiXinLogin();
        login.weiXinLogin();
    }
}

对象适配器

public interface SiginLogin{
    public void login();
}
public class LoginService implements SiginLogin{
    public void login(){
        System.out.println("普通的login");
    }
}
public class otherLogin{
    private SiginLogin siginLogin;
    public otherLogin(SiginLogin singinLogin){
        this.siginLogin=siginLogin;
    }
    public void otherLoginMethod(){
        siginLogin.login();
    }
}
public class Test{
    public static void main(String[] args){
        SiginLogin login=new LoginService();
        otherLogin otherLogin=new OtherLogin(login);
        otherLogin.otherLoginMethod();
    }
}

抽象对象适配器

public interface SampleOperation {
    public void option1();
    public void option2();
    public void option3();
}
public abstract class DefaultAdpter implements SampleOperation{
    public abstract void  option1();
    public abstract void  option2();
    public abstract void  option3();
}
public class Operator{
    private SampleOperation sampleOperation;
    public void addOperation(SampleOpration sampleOperation){
        this.sampleOpration=sampleOpration;
    }
    public void option1(){
        System.out.println("option1方法");
    }
    public void option2(){
        System.out.println("option2方法");
    }
    public void option3(){
        System.out.println("option3方法");
    }
}
public class Test{
    public static void main(String[] args){
        Operator operator=new Operator();
        operator.addOperation(new DefaultAdpter(){
            public void option1(){
                System.out.println("新的方法")
            }
        })
    }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值