簡單工廠模式,工廠方法模式,抽象工廠模式
阿新 • • 發佈:2018-12-13
個人認為比起文字解釋,用類圖、程式碼和執行結果更能瞭解和感受設計模式的思想。
簡單工廠模式
public interface Shape { void draw(); } public class Triangle implements Shape { @Override public void draw() { System.out.println("draw Triangle"); } } public class Circle implements Shape { @Override public void draw() { System.out.println("draw circle"); } } public class ShapeFactory { public static String CIRCLE = "circle"; public static String TRIANGLE = "triangle"; public static Shape createShape(String name) { Shape shape = null; Optional<String> nameOption = Optional.ofNullable(name); if (nameOption.isPresent()) { switch (nameOption.get()) { case "circle": shape = new Circle(); break; case "triangle": shape = new Triangle(); break; default: break; } } return shape; } } @SpringBootTest public class PatternTest { @Test public void createShapeTest() { Shape circle = ShapeFactory.createShape(ShapeFactory.CIRCLE); circle.draw(); Shape triangle = ShapeFactory.createShape(ShapeFactory.TRIANGLE); triangle.draw(); } }
工廠方法模式
public interface ShapeFactory { Shape createShape(); } public class CircleFactory implements ShapeFactory{ @Override public Shape createShape() { return new Circle(); } } public class TriangleFactory implements ShapeFactory { @Override public Shape createShape() { return new Triangle(); } } @Test public void factoryTest() { ShapeFactory circleFactory = new CircleFactory(); Shape circle = circleFactory.createShape(); circle.draw(); ShapeFactory triangleFactory = new TriangleFactory(); Shape triangle = triangleFactory.createShape(); triangle.draw(); }
抽象工廠模式
public interface Color { void paint(); } public class Red implements Color { @Override public void paint() { System.out.println("paint red"); } } public class White implements Color { @Override public void paint() { System.out.println("paint white"); } } public interface ShapeColorFactory { Shape createShape(); Color createColor(); } public class RedCircleFactory implements ShapeColorFactory { @Override public Shape createShape() { return new Circle(); } @Override public Color createColor() { return new Red(); } }