抽象工厂模式(Abstract Factory)
来源:互联网 发布:淘宝3.9包邮怎么赚钱 编辑:程序博客网 时间:2024/05/02 07:09
提供一个创建一系列相关或相互依赖的对象的接口,而不需指定它们具体的类。
通常在run-time式创建一个ConcreateFactory类的单体实例。这个ConcreteFactory创建ConcreteProduct对象。为了创建不同的ConcreteProduct对象,clients需要使用不同的ConcreteFactory。
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
Lion eats Wildebeest
Wolf eats Bison
- 抽象工厂(Abstract Factory)模式
- 抽象工厂模式(Abstract Factory)
- 抽象工厂(Abstract Factory)模式
- 抽象工厂模式(Abstract Factory)
- 抽象工厂模式(Abstract Factory)
- 抽象工厂模式(Abstract Factory)
- 2--抽象工厂模式(Abstract Factory)
- 抽象工厂模式(abstract factory pattern)
- 抽象工厂模式(Abstract Factory Pattern)
- 抽象工厂模式(Abstract Factory)
- 抽象工厂模式(Abstract Factory)
- 抽象工厂模式(Abstract Factory)
- 抽象工厂模式(Abstract Factory)
- 抽象工厂模式(Abstract Factory)
- 抽象工厂模式(Abstract Factory)
- 抽象工厂模式(Abstract Factory)
- 抽象工厂模式(Abstract Factory)
- 抽象工厂模式(Abstract Factory)
- XML Schema 概述
- 大学生,我们被谁抛弃?
- C#学习笔记一--C#中的参数传递
- 图象按比例
- 大学生,我们被抛弃?
- 抽象工厂模式(Abstract Factory)
- JS特效
- JBuiler中如何使用Borland的工具包
- Java虚拟机类装载:原理、实现与应用
- Windows下的函数hook技术
- 他们都是向阳花
- 正则表达式从入门到精通(zz)
- 国产游戏,何去何从?
- 050829