public class Singleton {
// 1. 私有静态实例,volatile 保证多线程可见性
private static volatile Singleton instance;
// 2. 私有构造方法
private Singleton() {}
// 3. 双重检查锁定(Double-Checked Locking)
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
// 抽象产品
interface Product {
void use();
}
// 具体产品A
class ConcreteProductA implements Product {
public void use() {
System.out.println("Using Product A");
}
}
// 抽象工厂
abstract class Creator {
public abstract Product createProduct();
}
// 具体工厂A
class ConcreteCreatorA extends Creator {
public Product createProduct() {
return new ConcreteProductA();
}
}
// 抽象产品族:按钮和文本框
interface Button { void render(); }
interface TextBox { void input(); }
// Windows 风格产品
class WindowsButton implements Button {
public void render() { System.out.println("Windows Button"); }
}
class WindowsTextBox implements TextBox {
public void input() { System.out.println("Windows TextBox"); }
}
// 抽象工厂接口
interface GUIFactory {
Button createButton();
TextBox createTextBox();
}
// Windows 工厂
class WindowsFactory implements GUIFactory {
public Button createButton() { return new WindowsButton(); }
public TextBox createTextBox() { return new WindowsTextBox(); }
}
class Computer {
private String CPU;
private String RAM;
// 其他组件...
// 建造者内部类
public static class Builder {
private String CPU;
private String RAM;
public Builder setCPU(String cpu) {
this.CPU = cpu;
return this; // 链式调用
}
public Builder setRAM(String ram) {
this.RAM = ram;
return this;
}
public Computer build() {
Computer computer = new Computer();
computer.CPU = this.CPU;
computer.RAM = this.RAM;
return computer;
}
}
}
// 使用
Computer computer = new Computer.Builder()
.setCPU("Intel i7")
.setRAM("32GB")
.build();
class Prototype implements Cloneable {
private String data;
public Prototype(String data) {
this.data = data;
}
@Override
public Prototype clone() {
try {
return (Prototype) super.clone();
} catch (CloneNotSupportedException e) {
return null;
}
}
}
// 使用
Prototype original = new Prototype("Original Data");
Prototype copy = original.clone();
// 旧接口(不兼容)
class LegacyPrinter {
void printDocument(String text) {
System.out.println("Legacy Printer: " + text);
}
}
// 新接口
interface ModernPrinter {
void print(String content);
}
// 适配器类
class PrinterAdapter implements ModernPrinter {
private LegacyPrinter legacyPrinter = new LegacyPrinter();
public void print(String content) {
legacyPrinter.printDocument(content);
}
}
// 基础组件
interface Coffee {
double getCost();
String getDescription();
}
// 具体组件
class SimpleCoffee implements Coffee {
public double getCost() { return 1.0; }
public String getDescription() { return "Simple Coffee"; }
}
// 装饰器基类
abstract class CoffeeDecorator implements Coffee {
protected Coffee decoratedCoffee;
public CoffeeDecorator(Coffee coffee) {
this.decoratedCoffee = coffee;
}
}
// 具体装饰器:加牛奶
class MilkDecorator extends CoffeeDecorator {
public MilkDecorator(Coffee coffee) { super(coffee); }
public double getCost() { return decoratedCoffee.getCost() + 0.5; }
public String getDescription() { return decoratedCoffee.getDescription() + ", Milk"; }
}
// 使用
Coffee coffee = new MilkDecorator(new SimpleCoffee());
BufferedReader
包装 FileReader
)interface Image {
void display();
}
// 真实对象(高成本)
class RealImage implements Image {
private String filename;
public RealImage(String filename) {
this.filename = filename;
loadFromDisk();
}
private void loadFromDisk() {
System.out.println("Loading image: " + filename);
}
public void display() {
System.out.println("Displaying image: " + filename);
}
}
// 代理类(延迟加载)
class ProxyImage implements Image {
private RealImage realImage;
private String filename;
public ProxyImage(String filename) { this.filename = filename; }
public void display() {
if (realImage == null) {
realImage = new RealImage(filename);
}
realImage.display();
}
}
// 主题(被观察者)
interface Subject {
void registerObserver(Observer o);
void removeObserver(Observer o);
void notifyObservers();
}
// 具体主题(例如天气数据)
class WeatherData implements Subject {
private List<Observer> observers = new ArrayList<>();
private float temperature;
public void setTemperature(float temp) {
this.temperature = temp;
notifyObservers();
}
public void registerObserver(Observer o) { observers.add(o); }
public void removeObserver(Observer o) { observers.remove(o); }
public void notifyObservers() {
for (Observer o : observers) {
o.update(temperature);
}
}
}
// 观察者接口
interface Observer {
void update(float temperature);
}
// 具体观察者(例如显示设备)
class DisplayDevice implements Observer {
public void update(float temperature) {
System.out.println("Current Temperature: " + temperature);
}
}
// 策略接口
interface PaymentStrategy {
void pay(int amount);
}
// 具体策略:信用卡支付
class CreditCardPayment implements PaymentStrategy {
public void pay(int amount) {
System.out.println("Paid " + amount + " via Credit Card");
}
}
// 上下文类(使用策略)
class ShoppingCart {
private PaymentStrategy strategy;
public void setPaymentStrategy(PaymentStrategy strategy) {
this.strategy = strategy;
}
public void checkout(int amount) {
strategy.pay(amount);
}
}
// 使用
ShoppingCart cart = new ShoppingCart();
cart.setPaymentStrategy(new CreditCardPayment());
cart.checkout(100);
abstract class Handler {
protected Handler nextHandler;
public void setNext(Handler handler) {
this.nextHandler = handler;
}
public abstract void handleRequest(int request);
}
// 具体处理者A
class ConcreteHandlerA extends Handler {
public void handleRequest(int request) {
if (request <= 10) {
System.out.println("Handler A processes request " + request);
} else if (nextHandler != null) {
nextHandler.handleRequest(request);
}
}
}
// 使用
Handler chain = new ConcreteHandlerA();
chain.setNext(new ConcreteHandlerB());
chain.handleRequest(5); // 由A处理
chain.handleRequest(20); // 由B处理
希望这些详细的解释和代码示例能帮助你深入理解设计模式!如果需要某个模式的进一步扩展,可以告诉我。