设计模式之抽象工厂
package com.ywx.abstractfactory; import com.ywx.abstractproduct.ICat; import com.ywx.abstractproduct.IDog; public interface IAnimalFactory { ICat createCat(); IDog createDog(); }
package com.ywx.concretefactory; import com.ywx.abstractfactory.IAnimalFactory; import com.ywx.abstractproduct.ICat; import com.ywx.abstractproduct.IDog; import com.ywx.concreteproduct.BlackCat; import com.ywx.concreteproduct.BlackDog; public class BlackAnimalFactory implements IAnimalFactory{ @Override public ICat createCat() { return new BlackCat(); } @Override public IDog createDog() { return new BlackDog(); } }
package com.ywx.concretefactory; import com.ywx.abstractfactory.IAnimalFactory; import com.ywx.abstractproduct.ICat; import com.ywx.abstractproduct.IDog; import com.ywx.concreteproduct.WhiteCat; import com.ywx.concreteproduct.WhiteDog; public class WhiteAnimalFactory implements IAnimalFactory{ @Override public ICat createCat() { return new WhiteCat(); } @Override public IDog createDog() { return new WhiteDog(); } }
package com.ywx.abstractproduct; public interface ICat { public void eat(); }
package com.ywx.abstractproduct; public interface IDog { public void eat(); }
package com.ywx.concreteproduct; import com.ywx.abstractproduct.ICat; public class BlackCat implements ICat{ @Override public void eat(){ System.out.println("黑猫在吃东西!"); } }
package com.ywx.concreteproduct; import com.ywx.abstractproduct.IDog; public class BlackDog implements IDog{ @Override public void eat() { System.out.println("黑狗在吃饭!"); } }
package com.ywx.concreteproduct; import com.ywx.abstractproduct.ICat; public class WhiteCat implements ICat{ @Override public void eat(){ System.out.println("白猫在吃鱼!"); } }
package com.ywx.concreteproduct; import com.ywx.abstractproduct.IDog; public class WhiteDog implements IDog{ @Override public void eat() { System.out.println("白狗在吃骨头!"); } }
package com.ywx.client; import com.ywx.abstractfactory.IAnimalFactory; import com.ywx.abstractproduct.ICat; import com.ywx.abstractproduct.IDog; import com.ywx.concretefactory.BlackAnimalFactory; import com.ywx.concretefactory.WhiteAnimalFactory; public class Test { public static void main(String[] args) { IAnimalFactory blackAnimalFactory = new BlackAnimalFactory(); ICat blackCat = blackAnimalFactory.createCat(); blackCat.eat(); IDog blackDog = blackAnimalFactory.createDog(); blackDog.eat(); IAnimalFactory whiteAnimalFactory = new WhiteAnimalFactory(); ICat whiteCat = whiteAnimalFactory.createCat(); whiteCat.eat(); IDog whiteDog = whiteAnimalFactory.createDog(); whiteDog.eat(); } }