設(shè)計模式
裝飾器模式
-
定義接口
public interface Component { void doSomeThing(); } -
具體構(gòu)建角色
public class ConcreateCompnent implements Component { @Override public void doSomeThing() { System.out.println("A功能"); } } -
聲明裝飾器
public class Decorator implements Component { private Component component; Decorator(Component component) { this.component = component; } @Override public void doSomeThing() { component.doSomeThing(); } } -
裝飾類的具體實現(xiàn)
public class ConcratorDecorator1 extends Decorator { ConcratorDecorator1(Component component) { //必須傳入具體構(gòu)建角色才能夠裝飾 super(component); } @Override public void doSomeThing() { //在保留父類方法的同時拓展新的方法 super.doSomeThing(); this.doAnotherThing(); } public void doAnotherThing() { //拓展的新方法 System.out.println("功能B"); } } public class ConcratorDecorator2 extends Decorator { ConcratorDecorator2(Component component) { super(component); } @Override public void doSomeThing() { super.doSomeThing(); this.doAnotherThing(); } public void doAnotherThing() { System.out.println("功能C"); } } -
Test
Component component = new ConcratorDecorator2(new ConcratorDecorator1(new ConcreateCompnent())); //具體構(gòu)建對象new ConreateComponent()同時具有了裝飾器1和在裝飾器2所提供的拓展方法 component.doSomeThing();
單例模式
-
雙重檢查模式(線程安全)
class Singleton { private volatile static Singleton singleton; //不允許直接被外部調(diào)用構(gòu)造方法 private Singleton() { } public static Singleton getSingleton(){ if (singleton == null) { synchronized (Singleton.class) { if (singleton == null) { singleton = new Singleton(); } } } return singleton; } } -
靜態(tài)內(nèi)部類單例模式
class Singleton { private Singleton() { } public static Singleton getInstance() { return SingletonHolder.instance; } private static class SingletonHolder { private static final Singleton instance = new Singleton(); } }
-
枚舉單例
enum Sigleton{ Instance }
持續(xù)補充中