类别:
Creational Pattern
问题/动机
如何创建一套子类的问题(父类引用指向子类实例)
情形1:一个方法返回一个具体的子类
极端情况:1万个子类需要一万个方法吗
极端情况:如过再扩展一万个子类,还需要再增加一万个方法吗
极端情况:虽然有一万个子类,但只需要用到其中一个,其他9999个干陪着吗
情形2:一个方法返回一个父类
不管有多少子类,都可以用一个方法将其返回,可以通过一定的策略和配置文件达到不修改client的目的
方案
示例
/* 测试方法 */ public class FactoryPatternDemo { public static void main(String[] args) { Shape shape1 = ShapeFactory.getShape("CIRCLE"); shape1.draw(); Shape shape2 = ShapeFactory.getShape("RECTANGLE"); shape2.draw(); Shape shape3 = ShapeFactory.getShape("SQUARE"); shape3.draw(); } } /* 工厂返回类型,子类对象赋给父类引用 (向上转型) */ interface Shape { void draw(); } /* 矩形 */ class Rectangle implements Shape { @Override public void draw() { System.out.println("Inside Rectangle::draw() method."); } } /* 正方形 */ class Square implements Shape { @Override public void draw() { System.out.println("Inside Square::draw() method."); } } /* 圆 */ class Circle implements Shape { @Override public void draw() { System.out.println("Inside Circle::draw() method."); } } /* 简单工厂 */ class ShapeFactory { public static Shape getShape(String shapeType) { if (shapeType == null) { return null; } if (shapeType.equalsIgnoreCase("CIRCLE")) { return new Circle(); } else if (shapeType.equalsIgnoreCase("RECTANGLE")) { return new Rectangle(); } else if (shapeType.equalsIgnoreCase("SQUARE")) { return new Square(); } return null; } }
Inside Circle::draw() method. Inside Rectangle::draw() method. Inside Square::draw() method.
优化
抽象工厂模式
关键词
向上转型,简单参数
应用
package org.slf4j; [...] public final class LoggerFactory { [...] public static Logger getLogger(String name) { ILoggerFactory iLoggerFactory = getILoggerFactory(); return iLoggerFactory.getLogger(name); } [...] }
补充
静态工厂方法,见《Effective Java》
获取加密算法:
https://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html#KeyPairGenerator
import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; public class Test { public static void main(String[] args) throws NoSuchAlgorithmException { KeyPairGenerator instance = KeyPairGenerator.getInstance("RSA"); } }
获取证书工厂:
https://docs.oracle.com/javase/7/docs/api/java/security/cert/CertificateFactory.html
import java.security.cert.CertificateFactory; public class Test { public static void main(String[] args) throws Exception { CertificateFactory instance = CertificateFactory.getInstance("X.509"); } }
获取MXBean
java.lang.management.ManagementFactory.getMemoryMXBean()
- Factory pattern methodfactory pattern method typescript factory method in dofactory factory method 工厂factory模式method abstract factory pattern cpp constructors consider factory methods abstract factory pattern abstract工厂factory pattern typescript template pattern method creational factory pattern class