抽象工厂方法_将关联组件组装成产品
** * 印刷抽象工厂类 * @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设计模式案例
声明
引用该文档请注明出处