介绍几种常用的设计模式
单例模式,它的定义就是确保某一个类只有一个实例,并且提供一个全局访问点。
/** * @author lin.hongwen * @date 2020-05-08 */ public class Singleton { private static Singleton singleton; private Singleton() {} public static Singleton getInstance() { if (singleton == null) { synchronized (Singleton.class) { singleton = new Singleton(); } } return singleton; } }
工厂方法模式定义了一个创建对象的接口,但由子类决定要实例化的类是哪一个,也就是说工厂方法模式让实例化推迟到子类。
package com.iwhalecloud.isa.taskflow.operationsoffice.dao; /** * @author lin.hongwen * @date 2020-05-08 */ public class MyFactory { public static final int TYPE_MI = 1;// 大米 public static final int TYPE_YU = 2;// 油 public static final int TYPE_SC = 3;// 蔬菜 public static Food getFoods(int foodType) { switch (foodType) { case TYPE_MI: return new DaMi(); case TYPE_YU: return new You(); case TYPE_SC: default: return new ShuCai(); } } } abstract class Food { } class DaMi extends Food { } class You extends Food { } class ShuCai extends Food { }
所谓适配器模式就是将一个类的接口,转换成客户期望的另一个接口。它可以让原本两个不兼容的接口能够无缝完成对接。
/** * @author lin.hongwen * @date 2020-05-08 */ public class MyAdapter { private MyAdapterImpl adapterImpl; public MyAdapter(MyAdapterImpl myAdapterImpl) { this.adapterImpl = myAdapterImpl; } public void doSomething() { adapterImpl.doSomething(); } public static void main(String args[]) { new MyAdapter(new MyAdapterImpl()).doSomething(); } } class MyAdapterImpl { public void doSomething() { } }
装饰者模式,动态地将责任附加到对象上。若要扩展功能,装饰者提供了比继承更加有弹性的替代方案。虽然装饰者模式能够动态将责任附加到对象上,但是他会产生许多的细小对象,增加了系统的复杂度。
思路: SmallDog ---> Dog ----> Animal
|
--->Pet -----> Animal
/** * @author lin.hongwen * @date 2020-05-08 */ public class MyDecorator { public static void main(String[] args) { Animal animal = new SmallDog(new Pet()); animal.eat(); } } interface Animal { public void eat(); } class Pet implements Animal { @Override public void eat() { System.out.println("Pet eat food"); } } class Dog implements Animal { protected Animal animal; public Dog(Animal animal) { this.animal = animal; } @Override public void eat() { this.animal.eat(); } } class SmallDog extends Dog { public SmallDog(Animal animal) { super(animal); } public void eat() { System.out.println("SmallDog eat other food "); this.animal.eat(); } }
原文:https://www.cnblogs.com/linhongwenBlog/p/12853825.html