工厂模式
示例:
/* Product */
interface Animal {
void makeSound();
}
/* Concrete Product */
class Cat implements Animal {
@Override
public void makeSound() {
System.out.println("Cat: Meow Meow");
}
}
/* Concrete Product */
class Dog implements Animal {
@Override
public void makeSound() {
System.out.println("Dog: woof woof woof");
}
}
/* Creator */
interface Creator {
Animal CreateAnimal();
}
/* Concrete Creator */
class CatCreator implements Creator{
@Override
public Animal CreateAnimal() {
return new Cat();
}
}
/* Concrete Creator */
class DogCreator implements Creator{
@Override
public Animal CreateAnimal() {
return new Dog();
}
}
测试代码:
public class Task {
public static void main(String args[]){
Creator factory = new CatCreator();
Animal cat = factory.CreateAnimal();
cat.makeSound();
Creator factoryDog = new DogCreator();
Animal dog = factoryDog.CreateAnimal();
dog.makeSound();
}
}