标签:设计模式 style dog sys interface int 工厂模式 log blog
抽象工厂模式:提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。
1.
public interface Animal {
public void play();
}
public class Cat implements Animal{
@Override
public void play() {
System.out.println("cat");
}
}
public class Dog implements Animal{
@Override
public void play() {
System.out.println("dog");
}
}
2.
public interface Person{
public void eat();
}
public class Boy implements Person{
@Override
public void eat() {
System.out.println("coder");
}
}
public class Girl implements Person{
@Override
public void eat() {
System.out.println("eating.");
}
}
3.
public interface Producer {
Person createPerson();
Animal createAnimal();
}
public class PersonProducer implements Producer{
@Override
public Person createPerson() {
return new Boy();
}
@Override
public Animal createAnimal() {
return new Dog();
}
}
public class AnimalProducer implements Producer{
@Override
public Person createPerson() {
return new Girl();
}
@Override
public Animal createAnimal() {
return new Cat();
}
}
测试:
public class AbstractFactoryDemo {
public static void main(String[] args) {
Producer animalProducer = new AnimalProducer();
Animal cat = animalProducer.createAnimal();
Person girl = animalProducer.createPerson();
cat.play();
girl.eat();
Producer personProducer = new PersonProducer();
Animal dog = personProducer.createAnimal();
Person boy = personProducer.createPerson();
dog.play();
boy.eat();
}
}
标签:设计模式 style dog sys interface int 工厂模式 log blog
原文地址:http://www.cnblogs.com/emoji1213/p/7616153.html