简单工厂模式 – 恵玩科技

package Patern.com.lxgyx_01;

public class AnimalDemo {
    public static void main(String[] args) {
        //class use
        Dog d=new Dog();
        d.eat();
        Cat c=new Cat();
        c.eat();
        System.out.println("--------------");

        //User factory
        Animal a=AnimalFactory.createAnimal("dog");
        a.eat();

        a=AnimalFactory.createAnimal("cat");
        a.eat();
        a=AnimalFactory.createAnimal("pig");
        if (a!=null){
            a.eat();
        }else{
            System.out.println("Sorry,there is no this animal now.");
        }
    }
}
package Patern.com.lxgyx_01;

public class AnimalFactory {
    private AnimalFactory() {
    }

    public static Animal createAnimal(String type){
        if ("dog".equals(type)){
            return new Dog();
        }else if ("cat".equals(type)){
            return new Cat();
        }else {
            return null;
        }
    }
}

package Patern.com.lxgyx_01;

public abstract class Animal {
    public abstract void eat();
}
package Patern.com.lxgyx_01;

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

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

 

打赏作者