工厂模式

这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
在工厂模式中,我们在创建对象时不会对客户端暴露创建逻辑,并且是通过使用一个共同的接口来指向新创建的对象。

  • 1.举例制作果汁,首先提供两个接口类,果汁的种类和加冰多少。
public interface MakeIce {
    void putIce();
}

public interface MakeJuice {
    void juicing();
}
  • 2.提供水果类和冰多少的类,这里方便起见,我们都写成内部类。
// 水果类
public class Fruits {
    static final String TAG = Fruits.class.getSimpleName();

     public class Apple implements MakeJuice {

        @Override
        public void juicing() {
            Log.d(TAG, "Apple juice");
        }
    }

     public class Mango implements MakeJuice {

        @Override
        public void juicing() {
            Log.d(TAG, "Mango juice");
        }
    }

     public class Orange implements MakeJuice {

        @Override
        public void juicing() {
            Log.d(TAG, "Orange juice");
        }
    }
}
// 冰类
public class Ice {
    static final String TAG = Ice.class.getSimpleName();

    public class LittleIce implements MakeIce {
        @Override
        public void putIce() {
            Log.d(TAG, "little ice");
        }
    }

    public class MoreIce implements MakeIce {
        @Override
        public void putIce() {
            Log.d(TAG, "More ice");
        }
    }

    public class NoeIce implements MakeIce {
        @Override
        public void putIce() {
            Log.d(TAG, "No ice");
        }
    }
}
  • 3.对于水果类,生成一个水果类工厂,获取一种水果对应一种果汁。对于冰类,生成一个冰类工厂。
  • 3.1 果汁工厂
public class FruitsFactory {
    public MakeJuice getJuice(String want) {
        MakeJuice ret;
        switch (want) {
            case "apple":
                ret = new Fruits().new Apple();
                break;
            case "orange":
                ret = new Fruits().new Orange();
                break;
            case "mango":
                ret = new Fruits().new Mango();
                break;
            default:
                ret = new Fruits().new Apple();
                break;
        }
        return ret;
    }

    public MakeIce getIce(String want) {
        return null;
    }
}

  • 3.2 冰工厂
public class IceFactory{
    MakeIce ret;

    public MakeJuice getJuice(String want) {
        return null;
    }

    public MakeIce getIce(String want) {
        switch (want) {
            case "little":
                ret = new Ice().new LittleIce();
                break;
            case "more":
                ret = new Ice().new MoreIce();
                break;
            case "no":
                ret = new Ice().new NoeIce();
                break;
        }
        return ret;
    }
}
  • 最后,new 出对应工厂后,调用相应get即可。
public class FactoryTest {
    private void test(){
       FruitsFactory fruitsFactory = new FruitsFactory();
        MakeJuice makeJuice = fruitsFactory.getJuice("Fruits");

        IceFactory iceFactory = new IceFactory();
        MakeIce makeIce1 = iceFactory.getIce("no");
    }
}

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