Week3 - 练习
发布于: 2020 年 11 月 07 日
单例模式
常规模式对 JDK DCL和多线程方式进行改进,增加volatile避免乱序、对象部分初始化就被使用;
静态内部类从JDK cinit 方法机制,保证线程安全的懒汉模式;
常规模式
public class OneInstance { private OneInstance() throws InterruptedException { init(); } private static volatile OneInstance instance; private void init() throws InterruptedException { if (ab.compareAndSet(false, true)) { System.out.println("New Instance"); } } public static OneInstance getInstance() throws InterruptedException { if (instance == null) { synchronized (OneInstance.class) { if (instance == null) { instance = new OneInstance(); } } } else { System.out.println("already not null out."); } return instance; }}
静态内部类
public class OneInstance2 { private OneInstance2() { init(); } private void init() { System.out.println("GetInstance"); } private static class SingleTonHoler { private static OneInstance2 instance; static { instance = new OneInstance2(); } } public static OneInstance2 getInstance() throws InterruptedException { System.out.println("get+" + counter); OneInstance2 in2 = SingleTonHoler.instance; if (in2 == null) { System.out.println("No Initial!"); } else { System.out.println("Inited!"); } return in2; }}
组合模式打印
CommonComp 可以扩展,为简单打印,仅写1个类
import java.util.*;class test { public static void main(String[] args) { System.out.println("hello"); AnyComponent lable = new CommonComp("label", null); List<AnyComponent> winSub = new ArrayList<AnyComponent>(); winSub.add(lable); AnyComponent window = new CommonComp("window", winSub); window.print(); } public static abstract class AnyComponent { private List<AnyComponent> subComs = new ArrayList<AnyComponent>(); private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public List<AnyComponent> getSubComs() { return subComs; } public void setSubComs(List<AnyComponent> subComs) { this.subComs = subComs; } private AnyComponent() { } AnyComponent(String name, List<AnyComponent> subComs) { setName(name); setSubComs(subComs); } public void print() { System.out.println(getName()); if (!(subComs == null || subComs.isEmpty())) { for (AnyComponent c : subComs) { c.print(); } } } } public static class CommonComp extends AnyComponent { public CommonComp(){ super(); } public CommonComp(String name, List<AnyComponent> subComs) { super(name, subComs); } }}
划线
评论
复制
发布于: 2020 年 11 月 07 日阅读数: 60
版权声明: 本文为 InfoQ 作者【evildracula】的原创文章。
原文链接:【http://xie.infoq.cn/article/72b41671ce5209cee8f3e537f】。文章转载请联系作者。
evildracula
关注
还未添加个人签名 2019.07.29 加入
还未添加个人简介
评论