工厂模式

1.工厂模式:

项目中一般会这样写:

public static Api create(int type){

        switch (type) {

                case 1:

                return new ImplA();

                case 2:

                return new ImplB();

                case 3:

                return new ImplC();

                default:

                return new ImplC();

    }

}

这样写的话 后续如果需要添加更多类型,就需要写更多的case,有时新增的会忘记写return,会造成不必要的麻烦

其实可以这样写更优雅:

publicT creatProduct(Class clz)

{

        Api  api=null;

        try {

                api=(Api) Class.forName(clz.getName()).newInstance();

         } catch (InstantiationException | IllegalAccessException

                | ClassNotFoundException e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

        }

        return (T)api;

}

当然,这还不是最好,我们可以将调用层和建造层分离开,这就是抽象工厂模式

//实例需要建造的接口

public interface IApi {

        void newInstance();

}

//工厂建造接口

public interface IFactory {

        IApi create();

}

public class ImplA implements IApi{

        @Override

         public void newInstance() {

        }

}

//工厂实现类A

public class ImplAFactory implements IFactory {

        @Override

        public IApi create() {

                return new ImplA();

        }

}

//工厂实现类B

public class ImplBFactory implements IFactory {

        @Override

        public IApi create() {

                return new ImplB();

        }

}

//实际调用

public class Test {

        public static void main(String[] args) {

                IFactory factory=new ImplAFactory();

                factory.create().newInstance();

        }

}

你可能感兴趣的:(工厂模式)