您的位置:首页 > 新闻 > 热点要闻 > java设计模式-工厂模式

java设计模式-工厂模式

2025/3/4 23:47:10 来源:https://blog.csdn.net/qq_39323945/article/details/141396632  浏览:    关键词:java设计模式-工厂模式

工厂模式


工厂模式是一种常用的设计模式,它用于创建对象,而无需指定具体的类。抽象工厂模式(Abstract Factory Pattern)是工厂模式的一种,它提供了一种创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。在抽象工厂模式中,客户端不依赖于产品类实例是如何被创建、组合和表达的,只依赖于抽象工厂的接口。

以下是一个使用抽象工厂模式的简单案例,我们将创建一个图形界面的应用程序,这个应用程序支持两种风格的按钮和文本框:Windows风格和Mac风格。

定义产品接口
首先,我们定义按钮(Button)和文本框(TextField)的接口:

java

// Button 接口  
interface Button {  void paint();  
}  // TextField 接口  
interface TextField {  void paint();  
}
创建具体产品类
然后,为每个风格(Windows和Mac)实现这些接口:java
// Windows风格的按钮  
class WindowsButton implements Button {  @Override  public void paint() {  System.out.println("Windows Button painted.");  }  
}  // Windows风格的文本框  
class WindowsTextField implements TextField {  @Override  public void paint() {  System.out.println("Windows TextField painted.");  }  
}  // Mac风格的按钮  
class MacButton implements Button {  @Override  public void paint() {  System.out.println("Mac Button painted.");  }  
}  // Mac风格的文本框  
class MacTextField implements TextField {  @Override  public void paint() {  System.out.println("Mac TextField painted.");  }  
}

创建抽象工厂接口及具体工厂类
接着,我们定义一个抽象工厂接口,以及针对每种风格的具体工厂类:

java

// 抽象工厂接口  
interface GUIFactory {  Button createButton();  TextField createTextField();  
}  // Windows风格的工厂  
class WindowsFactory implements GUIFactory {  @Override  public Button createButton() {  return new WindowsButton();  }  @Override  public TextField createTextField() {  return new WindowsTextField();  }  
}  // Mac风格的工厂  
class MacFactory implements GUIFactory {  @Override  public Button createButton() {  return new MacButton();  }  @Override  public TextField createTextField() {  return new MacTextField();  }  
}

使用抽象工厂
最后,客户端代码通过抽象工厂接口创建一系列相关对象,而无需知道这些对象的具体类:

java

public class FactoryPatternDemo {  public static void main(String[] args) {  // 使用Windows风格的工厂  GUIFactory factory = new WindowsFactory();  Button button = factory.createButton();  TextField textField = factory.createTextField();  button.paint();  textField.paint();  // 改为使用Mac风格的工厂  factory = new MacFactory();  button = factory.createButton();  textField = factory.createTextField();  button.paint();  textField.paint();  }  
}

在这个例子中,客户端代码通过抽象工厂接口GUIFactory创建了不同风格的Button和TextField对象,而无需关心这些对象的具体实现类。这提供了高度的灵活性和可扩展性,使得添加新的风格(例如Linux风格)变得简单,只需添加新的具体产品类和工厂类即可。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com