复杂工厂模式 – 恵玩科技

package Patern.com.lxgyx_02;

public class AnimalDemo {
    public static void main(String[] args) {
        //need:I want to shopp a dog
        Factory f=new DogFactory();
        Animal a=f.createAnimal();

        a.eat();
        System.out.println("------");
        f=new CatFactory();
        a=f.createAnimal();
        a.eat();
    }
}

package Patern.com.lxgyx_02;

public interface Factory {
    public abstract Animal createAnimal();
}
package Patern.com.lxgyx_02;

public class CatFactory implements Factory {
    @Override
    public Animal createAnimal() {
        return new Cat();
    }
}
package Patern.com.lxgyx_02;

public class DogFactory implements Factory {
    @Override
    public Animal createAnimal() {
        return new Dog();
    }
}
package Patern.com.lxgyx_02;

public class Cat extends Animal {
    @Override
    public void eat() {
        System.out.println("Cat eat fish.");
    }
}
package Patern.com.lxgyx_02;

public class Dog extends Animal {
    @Override
    public void eat() {
        System.out.println("Dog eat bonds");
    }
}

 

打赏作者