标签:概述 维护 实例 anim abstract sys system void 简单工厂模式
A:简单工厂模式概述//动物抽象类
public abstract class Animal {
public abstract void eat();
}
//狗类
public class Dog extends Animal {
@Override
public void eat() {
System.out.println("狗吃饭");
}
}
//猫类
public class Cat extends Animal {
@Override
public void eat() {
System.out.println("猫喝水");
}
}
//工厂类
public class AnimalFactory {
private AnimalFactory(){}
//public static Dog createDog() {return new Dog();}
//public static Cat createCat() {return new Cat();}
//改进
public static Animal createAnimal(String animalName) {
if(“dog”.equals(animalName)) {}
else if(“cat”.equals(animale)) {
}else {
return null;
}
}
}
//测试类
/**
* @param args
*/
public static void main(String[] args) {
//Dog d = AnimalFactory.createDog();
Dog d = (Dog) AnimalFactory.createAnimal("dog");
d.eat();
Cat c = (Cat) AnimalFactory.createAnimal("cat");
c.eat();
}
标签:概述 维护 实例 anim abstract sys system void 简单工厂模式
原文地址:http://blog.51cto.com/357712148/2158256