提供一个创建一系列相关或相互依赖的对象的接口,而不需指定它们具体的类。
通常在run-time式创建一个ConcreateFactory类的单体实例。这个ConcreteFactory创建ConcreteProduct对象。为了创建不同的ConcreteProduct对象,clients需要使用不同的ConcreteFactory。
<shapetype id="_x0000_t75" stroked="f" filled="f" path="m@4@5l@4@11@9@11@9@5xe" o:preferrelative="t" o:spt="75" coordsize="21600,21600"></shapetype><stroke joinstyle="miter"></stroke><formulas></formulas><f eqn="if lineDrawn pixelLineWidth 0"></f><f eqn="sum @0 1 0"></f><f eqn="sum 0 0 @1"></f><f eqn="prod @2 1 2"></f><f eqn="prod @3 21600 pixelWidth"></f><f eqn="prod @3 21600 pixelHeight"></f><f eqn="sum @0 0 1"></f><f eqn="prod @6 1 2"></f><f eqn="prod @7 21600 pixelWidth"></f><f eqn="sum @8 21600 0"></f><f eqn="prod @7 21600 pixelHeight"></f><f eqn="sum @10 21600 0"></f><lock aspectratio="t" v:ext="edit"></lock><shape id="_x0000_i1025" style="WIDTH: 431.25pt; HEIGHT: 228pt" type="#_x0000_t75"></shape><imagedata o:title="" src="file:///C:%5CDOCUME~1%5CADMINI~1%5CLOCALS~1%5CTemp%5Cmsohtml1%5C01%5Cclip_image001.png"></imagedata>
AbstractFactory(ContinentFactory)
定义一个接口,用来创建抽象products。
ConcreteFactory(AfrciaFactory,AmericaFactory)
实现创建具体的Products。
AbstractProduct(Herbivore,Carnivore)
声明一个接口表示一种product类型
Product(Wildebeest,Lion,Bison,Wolf)
定义被相关Concrete factory创建的product对象
实现AbstractProduct接口
Client(AnimalWorld)
使用AbstractFactory和AbstractProduct类
代码:
//AbstractFactory
public interface ContinentFactory{
public Herbivore CreateHerbivore();
public Carnivore CreateCarnivore();
}
//ConcreteFactory
public class AfricaFactory implements ContinentFactory{
public Herbivore CreateHerbivore(){
return new Wildebeest();
}
public Carnivore CreateCarnivore(){
return new Lion();
}
}
public class AmericaFactory implements ContinentFactory{
public Herbivore CreateHerbivore(){
return new Bison();
}
public Carnivore CreateCarnivore(){
return new Wolf();
}
}
//AbstractProduct
public interface Herbivore{
}
public interface Carnivore{
public void Eat(Herbivore h);
}
//Product
public class Wildebeest implements Herbivore{
}
public class Lion implements Carnivore{
public void Eat(Herbivore h){
System.out.println(“Lion eats “ +h.getName());
}
}
public class Bison implements Herbivore{
}
public class Wolf implements Carnivore{
public void Eat(Herbivore h){
System.out.println(“Wolf eats “ +h.getName());
}
}
//Client
public class AnimalWorld{
private Herbivore herbivore;
private Carnivore carnivore;
public AnimalWorld(ContinentFactory factory){
carnivore=factory. CreateCarnivore();
herbivore=factory. CreateHerbivore();
}
//Mehtods
public void RunFoodChain(){
carnivore.Eat(herbivore);
}
public static void main(String[] args){
AnimalWorld world=new AnimalWorld(new AfricaFactory());
world.RunFoodChain();
world=new AnimalWorld(new AmericaFactory());
world.RunFoodChain();
}
Output
|