在Java编程中,设计模式是一种经过验证的解决方案,用于解决特定场景下的常见问题。创建型模式是设计模式的一个重要分支,它专注于对象的创建过程,使得系统更加灵活、可扩展和易于维护。本文将详细介绍几种常见的创建型模式及其实际应用场景。
创建型模式主要关注如何解耦对象的创建与使用,使程序更易于扩展和维护。常见的创建型模式包括单例模式(Singleton)、工厂方法模式(Factory Method)、抽象工厂模式(Abstract Factory)、建造者模式(Builder)和原型模式(Prototype)。
单例模式确保一个类只有一个实例,并提供一个全局访问点。这种模式适用于需要控制资源访问的场景,例如数据库连接池、线程池等。
public class SingletonLogger {
private static SingletonLogger instance;
private SingletonLogger() {}
public static SingletonLogger getInstance() {
if (instance == null) {
synchronized (SingletonLogger.class) {
if (instance == null) {
instance = new SingletonLogger();
}
}
}
return instance;
}
public void log(String message) {
System.out.println("Log: " + message);
}
}
// 使用示例
public class Main {
public static void main(String[] args) {
SingletonLogger logger = SingletonLogger.getInstance();
logger.log("This is a singleton logger.");
}
}
工厂方法模式定义了一个用于创建对象的接口,但让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。
// 抽象产品
interface Payment {
void pay();
}
// 具体产品
class Alipay implements Payment {
@Override
public void pay() {
System.out.println("Paying via Alipay...");
}
}
class WeChatPay implements Payment {
@Override
public void pay() {
System.out.println("Paying via WeChat...");
}
}
// 工厂类
abstract class PaymentFactory {
abstract Payment createPayment();
}
class AlipayFactory extends PaymentFactory {
@Override
Payment createPayment() {
return new Alipay();
}
}
class WeChatPayFactory extends PaymentFactory {
@Override
Payment createPayment() {
return new WeChatPay();
}
}
// 使用示例
public class Main {
public static void main(String[] args) {
PaymentFactory factory = new AlipayFactory();
Payment payment = factory.createPayment();
payment.pay(); // 输出:Paying via Alipay...
}
}
抽象工厂模式提供了一种创建一系列相关或依赖对象的接口,而无需指定它们具体的类。
// 抽象产品A
interface Button {
void render();
}
// 具体产品A1
class WindowsButton implements Button {
@Override
public void render() {
System.out.println("Rendering Windows Button...");
}
}
// 具体产品A2
class WebButton implements Button {
@Override
public void render() {
System.out.println("Rendering Web Button...");
}
}
// 抽象工厂
interface GUIFactory {
Button createButton();
}
// 具体工厂1
class WindowsFactory implements GUIFactory {
@Override
public Button createButton() {
return new WindowsButton();
}
}
// 具体工厂2
class WebFactory implements GUIFactory {
@Override
public Button createButton() {
return new WebButton();
}
}
// 使用示例
public class Main {
public static void main(String[] args) {
GUIFactory factory = new WindowsFactory();
Button button = factory.createButton();
button.render(); // 输出:Rendering Windows Button...
}
}
建造者模式将一个复杂对象的构建与其表示分离,使得同样的构建过程可以创建不同的表示。
// 复杂对象
class Report {
private String title;
private String content;
private String footer;
public Report(ReportBuilder builder) {
this.title = builder.title;
this.content = builder.content;
this.footer = builder.footer;
}
public void showReport() {
System.out.println("Title: " + title);
System.out.println("Content: " + content);
System.out.println("Footer: " + footer);
}
// 静态内部类:建造者
public static class ReportBuilder {
private String title;
private String content;
private String footer;
public ReportBuilder setTitle(String title) {
this.title = title;
return this;
}
public ReportBuilder setContent(String content) {
this.content = content;
return this;
}
public ReportBuilder setFooter(String footer) {
this.footer = footer;
return this;
}
public Report build() {
return new Report(this);
}
}
}
// 使用示例
public class Main {
public static void main(String[] args) {
Report report = new Report.ReportBuilder()
.setTitle("Monthly Report")
.setContent("This is the content of the report.")
.setFooter("Generated on: " + new java.util.Date())
.build();
report.showReport();
}
}
原型模式通过复制现有对象来创建新对象,而不是通过常规的构造函数。
import java.util.Date;
// 可克隆的对象
class Prototype implements Cloneable {
private Date date;
public Prototype(Date date) {
this.date = date;
}
public Date getDate() {
return date;
}
@Override
protected Object clone() throws CloneNotSupportedException {
Prototype prototype = (Prototype) super.clone();
prototype.date = (Date) this.date.clone(); // 深拷贝
return prototype;
}
}
// 使用示例
public class Main {
public static void main(String[] args) throws CloneNotSupportedException {
Prototype original = new Prototype(new Date());
Prototype cloned = (Prototype) original.clone();
System.out.println("Original Date: " + original.getDate());
System.out.println("Cloned Date: " + cloned.getDate());
}
}