1. 工厂模式(Factory Pattern)
用途:用于封装对象的创建过程,允许客户端通过调用工厂方法得到所需的对象,而不必关心具体的创建逻辑。
// 抽象产品接口
interface PaymentMethod {
void processPayment(double amount);
}
// 具体产品
class CreditCard implements PaymentMethod {
@Override
public void processPayment(double amount) {
System.out.println("Processing payment using credit card.");
}
}
class PayPal implements PaymentMethod {
@Override
public void processPayment(double amount) {
System.out.println("Processing payment using PayPal.");
}
}
// 工厂类
class PaymentFactory {
public static PaymentMethod create(String type) {
if ("credit_card".equals(type)) {
return new CreditCard();
} else if ("paypal".equals(type)) {
return new PayPal();
} else {
throw new IllegalArgumentException("Invalid payment method type");
}
}
}
// 客户端代码
public class Client {
public static void main(String[] args) {
PaymentMethod payment = PaymentFactory.create("credit_card");
payment.processPayment(100.0);
}
}
2. 单例模式(Singleton Pattern)
用途:确保一个类只有一个实例,并提供全局访问点。
// 单例类
public class Singleton {
// 创建 Singleton 类的一个对象
private static volatile Singleton instance;
// 让构造函数为 private,这样该类就不会被实例化
private Singleton() {}
// 获取唯一可用的对象
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
// 类的方法
public void showMessage() {
System.out.println("Hello World!");
}
}
// 客户端代码
public class SingletonPatternDemo {
public static void main(String[] args) {
// 不合法的构造函数
// 编译时错误:构造函数 Singleton() 是不可见的
// Singleton object = new Singleton();
// 获取唯一可用的对象
Singleton object = Singleton.getInstance();
// 显示消息
object.showMessage();
}
}
3. 装饰器模式(Decorator Pattern)
用途:动态地给一个对象添加一些额外的职责(behavior)。
// 原始组件接口
interface Beverage {
String getDescription();
double cost();
}
// 具体组件
class HouseBlend implements Beverage {
@Override
public String getDescription() {
return "House Blend Coffee";
}
@Override
public double cost() {
return 0.89;
}
}
// 装饰器抽象类
abstract class CondimentDecorator implements Beverage {
protected Beverage beverage;
public CondimentDecorator(Beverage beverage) {
this.beverage = beverage;
}
@Override
public String getDescription() {
return beverage.getDescription();
}
}
// 具体装饰器
class Mocha extends CondimentDecorator {
public Mocha(Beverage beverage) {
super(beverage);
}
@Override
public String getDescription() {
return beverage.getDescription() + ", Mocha";
}
@Override
public double cost() {
return 0.20 + beverage.cost();
}
}
// 客户端代码
public class DecoratorPatternDemo {
public static void main(String[] args) {
Beverage beverage = new HouseBlend();
System.out.println(beverage.getDescription() + " $" + beverage.cost());
Beverage mochaBeverage = new Mocha(beverage);
System.out.println(mochaBeverage.getDescription() + " $" + mochaBeverage.cost());
}
}