工厂模式分为工厂方法和抽象工厂。 应用场景 实例化对象,代替new操作。如下图为工厂模式描述。 代码示例 public class ToyFactory { public static Toy produceToy(int toyName) throws ToyNameNotFoundException { switch (toyName) { case Toy.CHICKEN: return new ChickenToy(); case Toy.DUCK: return new DuckToy(); default: throw new ToyNameNotFoundException("Can't find toyname with " + toyName); } } public static void main(String[] args) { try { ToyFactory.produceToy(Toy.CHICKEN).saySomething(); ToyFactory.produceToy(Toy.DUCK).saySomething(); ToyFactory.produceToy(3).saySomething(); } catch (ToyNameNotFoundException e) { e.printStackTrace(); } } } class ToyNameNotFoundException extends Throwable { public ToyNameNotFoundException(String message) { super(message); } } interface Toy { public static int CHICKEN = 0x1; public static int DUCK = 0x2; // 定义Toy可以完成某些功能 public void saySomething(); } class DuckToy implements Toy { @Override public void saySomething() { System.out.println("呱呱"); } } class ChickenToy implements Toy { @Override public void saySomething() { System.out.println("喔喔"); } }