Java常见设计模式
设计模式是一套解决软件设计问题的通用解决方案,它们是经过多年实践和经验总结得出的。设计模式帮助我们在软件开发中应对常见的设计挑战,提高代码可读性、可维护性和可扩展性。
1、工厂方法模式(Factory Method Pattern)
工厂方法模式用于创建对象的接口,但由子类决定要实例化的类是哪一个。这样,将对象的实例化延迟到子类,从而避免了直接使用new关键字创建对象。
示例代码:
// 抽象产品接口
interface Product {
void display();
}
// 具体产品A
class ConcreteProductA implements Product {
public void display() {
System.out.println("Concrete Product A");
}
}
// 具体产品B
class ConcreteProductB implements Product {
public void display() {
System.out.println("Concrete Product B");
}
}
// 抽象工厂
abstract class Factory {
public abstract Product createProduct();
}
// 具体工厂A
class ConcreteFactoryA extends Factory {
public Product createProduct() {
return new ConcreteProductA();
}
}
// 具体工厂B
class ConcreteFactoryB extends Factory {
public Product createProduct() {
return new ConcreteProductB();
}
}
public class Main {
public static void main(String[] args) {
Factory factoryA = new ConcreteFactoryA();
Product productA = factoryA.createProduct();
productA.display(); // Output: Concrete Product A
Factory factoryB = new ConcreteFactoryB();
Product productB = factoryB.createProduct();
productB.display(); // Output: Concrete Product B
}
}
2、装饰器模式(Decorator Pattern)
装饰器模式允许你在运行时动态地给对象添加额外的功能,而不需要修改其结构。
示例代码:
// 抽象组件
interface Component {
void operation();
}
// 具体组件
class ConcreteComponent implements Component {
public void operation() {
System.out.println("Concrete Component");
}
}
// 抽象装饰器
abstract class Decorator implements Component {
protected Component component;
public Decorator(Component component) {
this.component = component;
}
public void operation() {
component.operation();
}
}
// 具体装饰器A
class ConcreteDecoratorA extends Decorator {
public ConcreteDecoratorA(Component component) {
super(component);
}
public void operation() {
super.operation();
System.out.println("Decorator A");
}
}
// 具体装饰器B
class ConcreteDecoratorB extends Decorator {
public ConcreteDecoratorB(Component component) {
super(component);
}
public void operation() {
super.operation();
System.out.println("Decorator B");
}
}
public class Main {
public static void main(String[] args) {
Component component = new ConcreteComponent();
Component decoratorA = new ConcreteDecoratorA(component);
Component decoratorB = new ConcreteDecoratorB(decoratorA);
decoratorB.operation();
// Output:
// Concrete Component
// Decorator A
// Decorator B
}
}
3、观察者模式(Observer Pattern)
观察者模式定义了一种一对多的依赖关系,当一个对象的状态发生变化时,所有依赖它的对象都会得到通知并自动更新。
示例代码:
import java.util.ArrayList;
import java.util.List;
// 抽象主题(Subject)
interface Subject {
void addObserver(Observer observer);
void removeObserver(Observer observer);
void notifyObservers();
}
// 具体主题(ConcreteSubject)
class ConcreteSubject implements Subject {
private List<Observer> observers = new ArrayList<>();
private String state;
public void addObserver(Observer observer) {
observers.add(observer);
}
public void removeObserver(Observer observer) {
observers.remove(observer);
}
public void notifyObservers() {
for (Observer observer : observers) {
observer.update(state);
}
}
public void setState(String state) {
this.state = state;
notifyObservers();
}
}
// 抽象观察者(Observer)
interface Observer {
void update(String state);
}
// 具体观察者A(ConcreteObserverA)
class ConcreteObserverA implements Observer {
public void update(String state) {
System.out.println("Observer A: " + state);
}
}
// 具体观察者B(ConcreteObserverB)
class ConcreteObserverB implements Observer {
public void update(String state) {
System.out.println("Observer B: " + state);
}
}
public class Main {
public static void main(String[] args) {
Subject subject = new ConcreteSubject();
Observer observerA = new ConcreteObserverA();
Observer observerB = new ConcreteObserverB();
subject.addObserver(observerA);
subject.addObserver(observerB);
subject.setState("Hello World!");
// Output:
// Observer A: Hello World!
// Observer B: Hello World!
}
}
4、策略模式(Strategy Pattern)
策略模式定义了一系列算法,将每个算法封装成一个类,使它们可以互相替换。客户端可以独立地使用不同的策略,而不需要知道具体的实现细节。
示例代码:
// 抽象策略(Strategy)
interface PaymentStrategy {
void pay(int amount);
}
// 具体策略A(ConcreteStrategyA)
class CreditCardPayment implements PaymentStrategy {
private String cardNumber;
private String expiryDate;
public CreditCardPayment(String cardNumber, String expiryDate) {
this.cardNumber = cardNumber;
this.expiryDate = expiryDate;
}
public void pay(int amount) {
System.out.println("Paid $" + amount + " with Credit Card.");
}
}
// 具体策略B(ConcreteStrategyB)
class PayPalPayment implements PaymentStrategy {
private String email;
public PayPalPayment(String email) {
this.email = email;
}
public void pay(int amount) {
System.out.println("Paid $" + amount + " with PayPal.");
}
}
// 环境类(Context)
class ShoppingCart {
private PaymentStrategy paymentStrategy;
public void setPaymentStrategy(PaymentStrategy paymentStrategy) {
this.paymentStrategy = paymentStrategy;
}
public void checkout(int amount) {
paymentStrategy.pay(amount);
}
}
public class Main {
public static void main(String[] args) {
ShoppingCart cart = new ShoppingCart();
PaymentStrategy creditCardPayment = new CreditCardPayment("1234-5678-9012-3456", "12/25");
cart.setPaymentStrategy(creditCardPayment);
cart.checkout(100);
// Output: Paid $100 with Credit Card.
PaymentStrategy paypalPayment = new PayPalPayment("user@example.com");
cart.setPaymentStrategy(paypalPayment);
cart.checkout(50);
// Output: Paid $50 with PayPal.
}
}
5、单例模式(Singleton Pattern)
单例模式确保一个类只有一个实例,并提供全局访问点。这在需要共享资源或控制访问某些资源时非常有用。
示例代码:
// 懒汉式单例模式
class Singleton {
private static Singleton instance;
private Singleton() {}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
public void showMessage() {
System.out.println("Hello, I am a Singleton!");
}
}
public class Main {
public static void main(String[] args) {
Singleton singleton1 = Singleton.getInstance();
Singleton singleton2 = Singleton.getInstance();
System.out.println(singleton1 == singleton2); // Output: true
singleton1.showMessage(); // Output: Hello, I am a Singleton!
}
}
6、适配器模式(Adapter Pattern)
适配器模式将一个类的接口转换成客户端所期望的另一个接口。这样,原本因接口不兼容而不能在一起工作的类可以一起工作。
示例代码:
// 目标接口(Target)
interface MediaPlayer {
void play(String audioType, String fileName);
}
// 适配者类(Adaptee)
class AdvancedAudioPlayer {
public void playMp4(String fileName) {
System.out.println("Playing MP4 file: " + fileName);
}
public void playVlc(String fileName) {
System.out.println("Playing VLC file: " + fileName);
}
}
// 适配器类(Adapter)
class MediaAdapter implements MediaPlayer {
private AdvancedAudioPlayer advancedAudioPlayer;
public MediaAdapter(String audioType) {
if (audioType.equalsIgnoreCase("mp4")) {
advancedAudioPlayer = new AdvancedAudioPlayer();
}
}
public void play(String audioType, String fileName) {
if (audioType.equalsIgnoreCase("mp4")) {
advancedAudioPlayer.playMp4(fileName);
}
}
}
// 客户端代码
public class Main {
public static void main(String[] args) {
MediaPlayer mediaPlayer = new MediaAdapter("mp4");
mediaPlayer.play("mp4", "movie.mp4");
// Output: Playing MP4 file: movie.mp4
}
}
以上是一些常见设计模式的简单示例。设计模式在软件开发中是非常重要的,它们提供了通用的解决方案来解决特定类型的问题。希望这些例子能够帮助你更好地理解设计模式。