抽象工廠方法_將關聯組件組裝成產品 附錄 https://github.com/maikec/pattern 個人GitHub設計模式案例 聲明 引用該文檔請註明出處 ...
抽象工廠方法_將關聯組件組裝成產品
** * 印刷抽象工廠類 * @author maikec * 2019/5/20 */ public abstract class AbstractPrintingFactory { private static AbstractPrintingFactory ourInstance ; /** * 獲取工廠實例 * @param className 工廠類類名 * @return */ public static AbstractPrintingFactory getInstance(String className) { if (null == ourInstance){ ReentrantReadWriteLock.WriteLock writeLock = new ReentrantReadWriteLock().writeLock(); if (writeLock.tryLock()){ if (null == ourInstance){ try { ourInstance = (AbstractPrintingFactory) Class.forName(className).newInstance(); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { e.printStackTrace(); } } } } return ourInstance; } /** * 生產紙 * @return */ public abstract BasePaper createPaper(); /** * 生成顏料 * @return */ public abstract BasePigment createPigment(); /** * @param paper * @param pigment * 生成圖畫 * @return */ public abstract BaseDrawing createDrawing(BasePaper paper, BasePigment pigment); } /** * 圖畫 * @author maikec * 2019/5/20 */ @AllArgsConstructor public abstract class BaseDrawing { protected BasePaper paper; protected BasePigment pigment; @Getter private String name; } /** * 紙 * @author maikec * 2019/5/20 */ @Getter @Setter public abstract class BasePaper { protected String name; } /** * 顏料 * @author maikec * @date 2019/5/12 */ @Getter @Setter public abstract class BasePigment { protected String name; } /** * 預設印刷工廠類 * @author maikec * @date 2019/5/12 */ public class DefaultPrintingFactory extends AbstractPrintingFactory { public DefaultPrintingFactory(){ super(); }; @Override public BasePaper createPaper() { BasePaper paper = DefaultPaper.builder().build(); paper.setName("DefaultPaper"); return paper; } @Override public BasePigment createPigment() { BasePigment pigment = DefaultPigment.builder().build(); pigment.setName("DefaultPigment"); return pigment; } @Override public BaseDrawing createDrawing(BasePaper paper, BasePigment pigment) { return new DefaultDrawing(paper,pigment,"defaultDrawing"); } } /** * @author maikec * 2019/5/20 */ public class DefaultDrawing extends BaseDrawing { public DefaultDrawing(BasePaper paper, BasePigment pigment,String name) { super(paper, pigment,name); } } /** * 預設紙 * @author maikec * 2019/5/20 */ @Builder public class DefaultPaper extends BasePaper { } /** * @author maikec * @date 2019/5/12 */ @Builder public class DefaultPigment extends BasePigment { } /** * @author maikec * @date 2019/5/12 */ public class AbstractFactoryDemo { public static void main(String[] args) { AbstractPrintingFactory instance = DefaultPrintingFactory.getInstance(DefaultPrintingFactory.class.getName()); BasePaper paper = instance.createPaper(); BasePigment pigment = instance.createPigment(); System.out.println(instance.createDrawing(paper, pigment).getName()); } }
附錄
https://github.com/maikec/pattern 個人GitHub設計模式案例
聲明
引用該文檔請註明出處