/**
* 设计模式(2)
* 抽象工厂模式
*
* 工厂模式是常用的设计模式,适用于规模大而又需要灵活创建对象时
*
* 相对于普通工厂 , 该模式每次增加业务类时只需要额外增加一个对应工厂类即可
*/
// 一个宠物接口 + 2个实现类
interface Pets {
void run();
}
class Dogs implements Pets {
@Override
public void run() {
System.out.println("Dogs running...");
}
}
class Cats implements Pets {
@Override
public void run() {
System.out.println("Cats running...");
}
}
// 一个工厂接口 + 2个实现类
interface PetStore {
Pets buyPet();
}
class DogsStore implements PetStore {
@Override
public Pets buyPet() {
return new Dogs();
}
}
class CatsStore implements PetStore {
@Override
public Pets buyPet() {
return new Cats();
}
}
// Test
public class main {
public static void main(String[] argv) {
PetStore pd = new DogsStore();
Pets d = pd.buyPet();
d.run();
PetStore pc = new CatsStore();
Pets c = pc.buyPet();
c.run();
}
}
转载于:https://my.oschina.net/tasker/blog/812473