码迷,mamicode.com
首页 > 编程语言 > 详细

Java设计模式-抽象工厂模式(Abstract Factory)

时间:2015-03-19 11:39:54      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:工厂模式   java设计模式   设计模式   

目的:

提供一个接口来创建一族相互依赖的对象,不用明确指出实体类。

技术分享

什么时候用:

  • 一个系统不应当依赖于产品类实例如何被创建、组合和表达的细节,这对于所有形态的工厂模式都是重要的。
  • 这个系统的产品有多于一个的产品族,而系统只消费其中某一族的产品。
  • 同属于同一个产品族的产品是在一起使用的,这一约束必须在系统的设计中体现出来。
  • 系统提供一个产品类的库,所有的产品以同样的接口出现,从而使客户端不依赖于实现。

实际的例子:

示例代码:

public class App {
	public static void main(String[] args) {
		createKingdom(new ElfKingdomFactory());
		createKingdom(new OrcKingdomFactory());
	}

	public static void createKingdom(KingdomFactory factory) {
		King king = factory.createKing();
		Castle castle = factory.createCastle();
		Army army = factory.createArmy();
		System.out.println("The kingdom was created.");
		System.out.println(king);
		System.out.println(castle);
		System.out.println(army);
	}
}
public interface King {

}
public interface Castle {

}
public interface Army {

}
public interface Army {

}
<pre name="code" class="java">public interface KingdomFactory {

	Castle createCastle();

	King createKing();

	Army createArmy();

}

public class ElfKingdomFactory implements KingdomFactory {

	public Castle createCastle() {
		return new ElfCastle();
	}

	public King createKing() {
		return new ElfKing();
	}

	public Army createArmy() {
		return new ElfArmy();
	}

}
public class OrcKingdomFactory implements KingdomFactory {

	public Castle createCastle() {
		return new OrcCastle();
	}

	public King createKing() {
		return new OrcKing();
	}

	public Army createArmy() {
		return new OrcArmy();
	}

}
public class ElfArmy implements Army {

	@Override
	public String toString() {
		return "This is the Elven Army!";
	}

}
public class ElfKing implements King {

	@Override
	public String toString() {
		return "This is the Elven king!";
	}

}
public class ElfCastle implements Castle {

	@Override
	public String toString() {
		return "This is the Elven castle!";
	}

}
public class OrcArmy implements Army {

	@Override
	public String toString() {
		return "This is the Orcish Army!";
	}

}
public class OrcCastle implements Castle {

	@Override
	public String toString() {
		return "This is the Orcish castle!";
	}

}
public class OrcKing implements King {

	@Override
	public String toString() {
		return "This is the Orc king!";
	}

}

输出结果:
The kingdom was created.
This is the Elven king!
This is the Elven castle!
This is the Elven Army!
The kingdom was created.
This is the Orc king!
This is the Orcish castle!
This is the Orcish Army!

@斗大的熊猫












Java设计模式-抽象工厂模式(Abstract Factory)

标签:工厂模式   java设计模式   设计模式   

原文地址:http://blog.csdn.net/sinat_26227857/article/details/44453197

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!