工厂模式, 为了统一管理对象创建, 不对外暴露对象创建的具体逻辑. 使得同一族群的产品类由工厂同一创建管理.
第一步: 创建产品接口 ICar.java
- public interface ICar {
- void build();
- }
第二步: 创建产品对象实现产品接口 BMW3.java,BMW5.java,BMW7.java
- public class BMW3 implements ICar {
- @Override
- public void build() {
- System.out.println("bmw3 built");
- }
- }
其中 BMW5.java,BMW7.java 与上面的类一样, 只是名字不一样.
第三步: 创建对象工厂类 CarFactory.java
- public class CarFactory {
- public ICar create(String type) throws Exception {
- if (type.equalsIgnoreCase("bmw3")) {
- return new BMW3();
- } else if (type.equalsIgnoreCase("bmw5")) {
- return new BMW5();
- } else if (type.equalsIgnoreCase("bmw7")) {
- return new BMW7();
- } else {
- throw (new Exception("not found this type"));
- }
- }
- }
第四步: 使用
- public class Main {
- public static void main(String[] args) {
- CarFactory factory = new CarFactory();
- try {
- ICar bmw3 = factory.create("bmw3");
- bmw3.build();
- ICar bmw5 = factory.create("bmw5");
- bmw5.build();
- ICar bmw7 = factory.create("bmw7");
- bmw7.build();
- ICar bmw9 = factory.create("bmw9");
- bmw9.build();
- } catch (Exception e) {
- System.out.println(e.getMessage());
- }
- }
- }
来源: http://www.jianshu.com/p/f66cd002c80e