一、文件目录
二、代码
1、对象类
public interface IAnimal { default void eat(){ System.out.println("Animal eat"); }; } public class Cat implements IAnimal { } public class Dog implements IAnimal { } public class BlackCat extends Cat{ @Override public void eat() { System.out.println("Black Cat eat"); } } public class WhiteCat extends Cat { @Override public void eat() { System.out.println("White Cat eat"); } } public class BlackDog extends Dog{ @Override public void eat() { System.out.println("Black Dog eat"); } } public class WhiteDog extends Dog{ @Override public void eat() { System.out.println("White Dog eat"); } }
2、工厂类
public interface IAnimalFactory { Cat createCat(); Dog createDog(); } public class BlackAnimalFactory implements IAnimalFactory { @Override public Cat createCat() { return new BlackCat(); } @Override public Dog createDog() { return new BlackDog(); } } public class WhiteAnimalFactory implements IAnimalFactory { @Override public Cat createCat() { return new WhiteCat(); } @Override public Dog createDog() { return new WhiteDog(); } }
3、测试类
public class AbstractFactoryTest { public static void main(String[] args) { IAnimalFactory blackAnimalFactory = new BlackAnimalFactory(); Cat blanckCat = blackAnimalFactory.createCat(); Dog blanckDog = blackAnimalFactory.createDog(); blanckCat.eat(); blanckDog.eat(); IAnimalFactory whiteAnimalFactory=new WhiteAnimalFactory(); Cat whiteAnimalFactoryCat = whiteAnimalFactory.createCat(); Dog whiteAnimalFactoryDog = whiteAnimalFactory.createDog(); whiteAnimalFactoryCat.eat(); whiteAnimalFactoryDog.eat(); } }
Black Cat eat Black Dog eat White Cat eat White Dog eat