一、定义

为创建一组相关相互依赖的对象提供一个接口,而无需指定它们的具体类。

二、类图表示

抽象工厂模式

三、实现

1、Factory

package pattern.creational.abstractfactory;

/**
 * 抽象动物工厂 
 */
public abstract class AbstractAnimalFactory {

	//创建食草动物
	public abstract Herbivore createHerbivore();
	
	//创建食肉动物
	public abstract Carnivore createCarnivore();
}


package pattern.creational.abstractfactory;

/**
 * 亚洲动物工厂
 */
public class AsiaAnimalFactory extends AbstractAnimalFactory {

	@Override
	public Herbivore createHerbivore() {
		return new Deer();
	}

	@Override
	public Carnivore createCarnivore() {
		return new Tiger();
	}

}


package pattern.creational.abstractfactory;

/**
 * 非洲动物工厂
 */
public class AfricaAnimalFactory extends AbstractAnimalFactory {

	@Override
	public Herbivore createHerbivore() {
		return new Antelope();
	}

	@Override
	public Carnivore createCarnivore() {
		return new Cheetah();
	}

}

2、Product

package pattern.creational.abstractfactory;

/**
 * 食肉动物
 */
public abstract class Carnivore {

	public abstract void eat(Herbivore herbivore);
}


package pattern.creational.abstractfactory;

/**
 * 食草动物
 */
public abstract class Herbivore {

}


package pattern.creational.abstractfactory;

public class Tiger extends Carnivore {

	@Override
	public void eat(Herbivore herbivore) {
		System.out.println(String.format("%s 在亚洲森林中捕食 %s", this, herbivore));
	}

	@Override
	public String toString() {
		return "老虎";
	}
}


package pattern.creational.abstractfactory;

public class Cheetah extends Carnivore {

	@Override
	public void eat(Herbivore herbivore) {
		System.out.println(String.format("%s 在非洲大草原上追捕  %s", this, herbivore));
	}

	@Override
	public String toString() {
		return "猎豹";
	}
}


package pattern.creational.abstractfactory;

public class Deer extends Herbivore {

	@Override
	public String toString() {
		return "鹿";
	}
}


package pattern.creational.abstractfactory;

public class Antelope extends Herbivore {

	@Override
	public String toString() {
		return "羚羊";
	}
}

四、使用

package pattern.creational.abstractfactory;

public class AnimalWorld {

	private Herbivore herbivore;
	private Carnivore canivore;
	
	public AnimalWorld(AbstractAnimalFactory factory) {
		this.herbivore = factory.createHerbivore();
		this.canivore = factory.createCarnivore();
	}
	
	public void play(){
		canivore.eat(herbivore);
	}
}


package pattern.creational.abstractfactory;

public class Client {

	public static void main(String[] args) {
		//亚洲
		AbstractAnimalFactory factory = new AsiaAnimalFactory();
		AnimalWorld world = new AnimalWorld(factory);
		world.play();
		//非洲
		factory = new AfricaAnimalFactory();
		world = new AnimalWorld(factory);
		world.play();
	}
}

  • 程序输出:

老虎 在亚洲森林中捕食 鹿

猎豹 在非洲大草原上追捕 羚羊

五、适用场合

  • 创建一系列相关产品时使用
  • 只想显示提供的产品类库的接口而不是实现时
例如:场景切换(第一集播出亚洲动物世界,第二集播出非洲动物世界或换肤)