简单工厂模式-工厂方法模式-抽象工厂模式
简单工厂模式又称静态工厂模式
下面看代码示例:
public interface Robot {public void work();}
public class Factory {public static Robot create(Class<?> clazz) {try {Robot robot = (Robot)clazz.newInstance();return robot;} catch (Exception e) {e.printStackTrace();}return null;}}
public class Test {public static void main(String[] args) {Robot r1 = Factory.create(RobotA.class);r1.work();Robot r2 = Factory.create(RobotB.class);r2.work();}}class RobotA implements Robot {@Overridepublic void work() {System.out.println("A work");}}class RobotB implements Robot {@Overridepublic void work() {System.out.println("B work");}}