抽象工厂模式 --意图是为了提供一个接口创建一系列相关或者相互依赖对象,无需指定他们具体的类。
这个模式理解起来比较简单 接下来我们举一个例子来展示一下这个模式:
如果我们的wps文档需要一种可以更换皮肤的类,里面具有不同种类的风格各异的皮肤,类似于不同种类的按钮的类型,滚动条的类型,如果我们不给用户提供一个结构来构建这一系列的类的话,用户可能难以知道我们给出了哪些类是这个皮肤风格。为了解决这个问题我们使用的抽象工厂模式。
1.首先我们创建一个一堆按钮和滚动条的图元对象:
//所有按钮等组件的抽象父类
public interface Glyph {
}
-------------------------------------------------------------------------------------
//滚动条的父类
public interface ScrollBar extends Glyph{
//滚动条的滚动
public void ScrollTo();
}
-------------------------------------------------------------------------------------
//Motif风格的滚动条
public class MotifScrollBar implements ScrollBar{
@Override
public void ScrollTo() {
System.out.println("Motif风格的滚动条滚动了");
}
}
-------------------------------------------------------------------------------------
public class PMScrollBar implements ScrollBar{
@Override
public void ScrollTo() {
System.out.println("PM风格的滚动条滚动了");
}
}
-------------------------------------------------------------------------------------
public interface Button extends Glyph{
//按下按钮操作
public void Press();
}
-------------------------------------------------------------------------------------
public class PMButton implements Button{
@Override
public void Press() {
System.out.println("PM风格的按钮点击了");
}
}
-------------------------------------------------------------------------------------
public class MotifButton implements Button{
@Override
public void Press() {
System.out.println("Motif风格的按钮点击了");
}
}
2.创建一系列的抽象工厂
//抽象工厂的最大父类
public interface GUIFactory {
public Glyph CreateScrollBar();
public Glyph CreateButton();
}
-------------------------------------------------------------------------------------
//Motif风格的工厂
public class MotifFactory implements GUIFactory{
@Override
public Glyph CreateScrollBar() {
return new MotifScrollBar();
}
@Override
public Glyph CreateButton() {
return new MotifButton();
}
}
-------------------------------------------------------------------------------------
public class PMFactory implements GUIFactory{
@Override
public Glyph CreateScrollBar() {
return new PMScrollBar();
}
@Override
public Glyph CreateButton() {
return new PMButton();
}
}
3.最后我们使用我们的抽象工厂
public class Main {
public static void main(String[] args){
//通过工厂创建我们的各个风格的按钮
MotifFactory motifyFactory=new MotifFactory();
PMFactory pmFactory=new PMFactory();
MotifButton motifButton=(MotifButton) motifyFactory.CreateButton();
motifButton.Press();//点击按钮事件
MotifScrollBar motifScrollBar=(MotifScrollBar) motifyFactory.CreateScrollBar();
motifScrollBar.ScrollTo();//滚动条滚动事件
PMButton pmButton=(PMButton) pmFactory.CreateButton();
pmButton.Press();//点击按钮事件
PMScrollBar PMScrollBar=(PMScrollBar) pmFactory.CreateScrollBar();
PMScrollBar.ScrollTo();//滚动条滚动事件
}
}
4.运行结果
我们使用了抽象工厂方法,当然这样看可能看不出它的优点,但是如果类多了起来,它就能很好的帮我们的用户区分开不同的图元,让用户不用关系具体的类,只需要调用我们的接口使用即可。
它的缺点就是难以扩展,如果我们需要新的不同种类的,比如说一个菜单,就需要修改我们的每一个抽象工厂,很难去扩充。