抽象工厂模式具备的一个特点就是它支持的工厂具备生产多种产品族的能力,而工厂方法模式只能创造出来一类产品,这是两者之间的最大区别。
为了说明抽象工厂模式的设计方法,下面采用一个可以跨平台的具有图形用户界面的软件来演示其结构。在windows下外观呈windows组件的样子,但在UNIX下,外观呈Motif组件的样子。其上的按钮,滚动条等外观虽然会不一样,但是功能相同。抽象工厂模式的参与者有:抽象工厂角色,具体工厂角色,抽象产品角色,具体产品角色。下面展示代码。
抽象按钮:
Button.java
public abstract class Button{
private String type="按钮";
private String lookAndFeel;
public String getLookAndFeel(){
return lookAndFeel;
}
public void setlookAndFeel(String lookAndFeel){
this.lookAndFeel=lookAndFeel;
}
public String getType(){
return type;
}
public void setType(String type){
this.type=type;
}
public void show(){
System.out.println("显示"+lookAndFeel+"风格的"+"type");
}
}
Windows风格的按钮:
WindowsButton.java
public class WindowsButton extends Button{
public WindowsButton(){
super();
this.setLookAndFeel("Windows");
}
}
Motif风格的按钮:
MotifButton.java
public class MotifButton extends Button{
public MotifButton(){
super();
this.setLookAndFeel("Motif");
}
}
抽象滚动条:
Scroll.java
public abstract class Scroll{
private String type="滚动条";
private String lookAndFeel;
public String getLookAndFeel(){
return lookAndFeel;
}
public void setLookAndFeel(String lookAndFeel){
this.loolAndFeel=lookAndFeel;
}
public String getType(){
return type;
}
public void setType(String type){
this.type=type;
}
public void show(){
System.out.println("显示"+lookAndFeel+"风格的"+type);
}
}
Windows风格的滚动条:
WindowsScroll.java
public class WindowsScroll extends Scroll{
public WindowsScroll(){
super();
this.setLookAndFeel("Windows");
}
}
Motif风格的滚动条:
MotifScroll.java
public class MotifScroll extends Scroll{
public MotifScroll(){
super();
this.setLookAndFeel("Motif");
}
}
抽象工厂抽象类:
ComponentFactory.java
public abstract class ComponentFactory{
public abstract Button createButton();
public abstract Scroll creaScroll();
}
Windows控件工厂:
WindowsComponentFactory.java
public class WindowsComponentFactory extends ComponentFactory{
@override
public Scroll creaScroll(){
return new WindowsScroll();
}
@override
public Button createButton(){
return new WindowsButton();
}
}
Motif控件工厂
MotifComponentFactory.java
public class MotifComponentFactory extends ComponentFactory{
@override
public Scroll creaScroll(){
return new MotifScroll();
}
@override
public Button createButton(){
return new MotifButton();
}
}
客户端代码:
Client.java
public class Client{
public static void main(String[] args){
ComponentFactory factory;
Button button;
Scroll scroll;
factory=new WindowsComponentFactory();
button=factory.createButton();
scroll=factory.creaScroll();
button.show();
scroll.show();
factory=new MotifComponentFactory();
button=factory.createButton();
scroll=factory.creaScroll();
button.show();
scroll.show();
}
}
客户端代码运行结果如下:
显示Windows风格的按钮
显示Windows风格的滚动条
显示Motif风格的按钮
显示Motif风格的滚动条
转载于:https://blog.51cto.com/secondscript/1580951