抽象工厂是简单工厂的工厂方法的结合。
具体来说, 和工厂方法比较
工厂方法:一个工厂对应一个产品实例化。
抽象方法:一个工厂对应一系列产品实例化。
public class SingleFantasy {
public static void main(String[] args) {
ColaChickenFactory colaChickenFactory = new ColaChickenFactory();
CurryChickenFactory curryChickenFactory = new CurryChickenFactory();
Chicken chicken = colaChickenFactory.getChicken();
Duck duck = colaChickenFactory.getDuck();
Chicken chicken1 = curryChickenFactory.getChicken();
Duck duck1 = curryChickenFactory.getDuck();
System.out.println(chicken.getClass().getName());
System.out.println(chicken1.getClass().getName());
}
}
abstract class Chicken {
protected String name;
}
abstract class Duck {
protected String name;
}
class ColaChicken extends Chicken {
}
class ColaDuck extends Duck {
}
class CurryChicken extends Chicken {
}
class CurryDuck extends Duck {
}
abstract class Factory {
public abstract Chicken getChicken();
public abstract Duck getDuck();
}
class ColaChickenFactory extends Factory{
@Override
public Chicken getChicken() {
return new ColaChicken();
}
@Override
public Duck getDuck() {
return new ColaDuck();
}
}
class CurryChickenFactory extends Factory{
@Override
public Chicken getChicken() {
return new CurryChicken();
}
@Override
public Duck getDuck() {
return new CurryDuck();
}
}