/**
* 工厂方法模式:
* 优点:
* 不需要更改已经存在的代码
* 缺点:
* 代码量大
*
*/
public class Demo03_Factory {
public static void main(String[] args) {
Animal a1 = new CatFactory().getAnimal();
Animal a2 = new DogFactory().getAnimal();
Animal a3 = new SnakeFactory().getAnimal();
}
}
class Animal {}
class Cat extends Animal {}
class Dog extends Animal {}
class Snake extends Animal {}
interface AnimalFactory {
Animal getAnimal();
}
class CatFactory implements AnimalFactory {
@Override
public Animal getAnimal() {
return new Cat();
}
}
class DogFactory implements AnimalFactory {
@Override
public Animal getAnimal() {
return new Dog();
}
}
class SnakeFactory implements AnimalFactory {
@Override
public Animal getAnimal() {
return new Snake();
}
} |
|