设计模式

工厂模式

2017-09-19  本文已影响3人  jfson_土豆

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

public interface MakeIce {
    void putIce();
}

public interface MakeJuice {
    void juicing();
}
// 水果类
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");
        }
    }
}
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;
    }
}

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;
    }
}
public class FactoryTest {
    private void test(){
       FruitsFactory fruitsFactory = new FruitsFactory();
        MakeJuice makeJuice = fruitsFactory.getJuice("Fruits");

        IceFactory iceFactory = new IceFactory();
        MakeIce makeIce1 = iceFactory.getIce("no");
    }
}
上一篇 下一篇

猜你喜欢

热点阅读