本帖最后由 小刀葛小伦 于 2019-9-12 14:25 编辑一.设计模式-单例模式1.懒汉单例模式 [Java] 纯文本查看 复制代码 ? 01 02 03 04 05 06 07 08 09 10 11 12 13 14 public class LazySingleton { //保证 instance 在所有线程中同步 private static volatile LazySingleton instance= null ; //避免类在外部被实例化 private LazySingleton(){} public static synchronized LazySingleton getInstance() { //getInstance 方法前加同步 if (instance== null ) { instance= new LazySingleton(); } return instance; } } 2.饿汉单例模式 [Java] 纯文本查看 复制代码 ? 1 2 3 4 5 6 7 8 public class HungrySingleton { private static final HungrySingleton instance= new HungrySingleton(); private HungrySingleton(){} public static HungrySingleton getInstance() { return instance; } } 二.设计模式-装饰模式1.统一的接口: [Java] 纯文本查看 复制代码 ? 1 2 3 4 5 6 public abstract class Component { /** * 基本的操作类 */ public abstract void opeartion(); } 2.其中的一个拓展实现类,作为一个拓展的功能类 [Java] 纯文本查看 复制代码 ? 1 2 3 4 5 6 public class ConcreteComponent extends Component { @Override public void opeartion() { System.out.println( "具体对象的操作" ); } } 3.另一个拓展的功能类 [Java] 纯文本查看 复制代码 ? 01 02 03 04 05 06 07 08 09 10 @Setter public class Decorator extends Component{ private Componentcomponent; @Override public void opeartion() { if (component != null ){ component.opeartion(); } } } 4.操作类A [Java] 纯文本查看 复制代码 ? 1 2 3 4 5 6 7 8 9 public class ConcreteDecoratorA extends Decorator { private StringaddedState; @Override public void opeartion() { super .opeartion(); addedState = "New State" ; System.out.println( "具体的装饰对象A的操作" ); } } 5.操作类B [Java] 纯文本查看 复制代码 ? 01 02 03 04 05 06 07 08 09 10 11 12 public class ConcreteDecoratorB extends Decorator { @Override public void opeartion() { super .opeartion(); AddedBehavior(); System.out.println( "具体装饰对象B的操作" ); } private void AddedBehavior(){ System.out.println( "装饰B独有的方法" ); } } 6.测试用例 [Java] 纯文本查看 复制代码 ? 01 02 03 04 05 06 07 08 09 10 public class Test { public static void main(String[] args) { ConcreteComponent component = new ConcreteComponent(); ConcreteDecoratorA decoratorA = new ConcreteDecoratorA(); ConcreteDecoratorB decoratorB = new ConcreteDecoratorB(); decoratorA.setComponent(component); decoratorB.setComponent(decoratorA); decoratorB.opeartion(); } }