Head First设计模式中的典型设计模式解析与案例分析
大家好,我是免费搭建查券返利机器人省钱赚佣金就用微赚淘客系统3.0的小编,也是冬天不穿秋裤,天冷也要风度的程序猿!
《Head First设计模式》是一本广受欢迎的书籍,以轻松有趣的方式介绍了设计模式的基本概念和应用场景。本文将解析其中的几个典型设计模式,并通过Java代码示例进行详细分析,帮助大家更好地理解和应用这些设计模式。
一、策略模式(Strategy Pattern)
策略模式定义了一系列算法,并将每个算法封装起来,使它们可以互换。策略模式使得算法可以独立于使用它的客户端而变化。
策略模式常用于需要在运行时选择不同算法的场景,比如排序算法、加密算法等。
示例代码:
package cn.juwatech.designpatterns.strategy;
interface QuackBehavior {
void quack();
}
class Quack implements QuackBehavior {
@Override
public void quack() {
System.out.println("Quack!");
}
}
class Squeak implements QuackBehavior {
@Override
public void quack() {
System.out.println("Squeak!");
}
}
class MuteQuack implements QuackBehavior {
@Override
public void quack() {
System.out.println("<< Silence >>");
}
}
class Duck {
private QuackBehavior quackBehavior;
public Duck(QuackBehavior quackBehavior) {
this.quackBehavior = quackBehavior;
}
public void performQuack() {
quackBehavior.quack();
}
public void setQuackBehavior(QuackBehavior quackBehavior) {
this.quackBehavior = quackBehavior;
}
}
public class StrategyPatternDemo {
public static void main(String[] args) {
Duck mallard = new Duck(new Quack());
mallard.performQuack();
Duck rubberDuck = new Duck(new Squeak());
rubberDuck.performQuack();
Duck decoy = new Duck(new MuteQuack());
decoy.performQuack();
}
}
二、观察者模式(Observer Pattern)
观察者模式定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。当主题对象发生变化时,所有依赖于它的观察者对象都会得到通知并更新。
观察者模式常用于需要根据某对象状态变化通知其他对象的场景,如事件监听、数据绑定等。
示例代码:
package cn.juwatech.designpatterns.observer;
import java.util.ArrayList;
import java.util.List;
interface Observer {
void update(float temp, float humidity, float pressure);
}
interface Subject {
void registerObserver(Observer o);
void removeObserver(Observer o);
void notifyObservers();
}
class WeatherData implements Subject {
private List<Observer> observers;
private float temperature;
private float humidity;
private float pressure;
public WeatherData() {
observers = new ArrayList<>();
}
@Override
public void registerObserver(Observer o) {
observers.add(o);
}
@Override
public void removeObserver(Observer o) {
observers.remove(o);
}
@Override
public void notifyObservers() {
for (Observer observer : observers) {
observer.update(temperature, humidity, pressure);
}
}
public void setMeasurements(float temperature, float humidity, float pressure) {
this.temperature = temperature;
this.humidity = humidity;
this.pressure = pressure;
notifyObservers();
}
}
class CurrentConditionsDisplay implements Observer {
private float temperature;
private float humidity;
private Subject weatherData;
public CurrentConditionsDisplay(Subject weatherData) {
this.weatherData = weatherData;
weatherData.registerObserver(this);
}
@Override
public void update(float temperature, float humidity, float pressure) {
this.temperature = temperature;
this.humidity = humidity;
display();
}
public void display() {
System.out.println("Current conditions: " + temperature + "F degrees and " + humidity + "% humidity");
}
}
public class ObserverPatternDemo {
public static void main(String[] args) {
WeatherData weatherData = new WeatherData();
CurrentConditionsDisplay currentDisplay = new CurrentConditionsDisplay(weatherData);
weatherData.setMeasurements(80, 65, 30.4f);
weatherData.setMeasurements(82, 70, 29.2f);
}
}
三、装饰者模式(Decorator Pattern)
装饰者模式动态地给对象添加一些额外的职责。装饰者模式提供了比继承更有弹性的替代方案。
装饰者模式常用于需要动态地扩展对象功能的场景,如Java I/O类的设计。
示例代码:
package cn.juwatech.designpatterns.decorator;
abstract class Beverage {
String description = "Unknown Beverage";
public String getDescription() {
return description;
}
public abstract double cost();
}
class Espresso extends Beverage {
public Espresso() {
description = "Espresso";
}
@Override
public double cost() {
return 1.99;
}
}
abstract class CondimentDecorator extends Beverage {
public abstract String getDescription();
}
class Mocha extends CondimentDecorator {
Beverage beverage;
public Mocha(Beverage beverage) {
this.beverage = beverage;
}
@Override
public String getDescription() {
return beverage.getDescription() + ", Mocha";
}
@Override
public double cost() {
return 0.20 + beverage.cost();
}
}
class Whip extends CondimentDecorator {
Beverage beverage;
public Whip(Beverage beverage) {
this.beverage = beverage;
}
@Override
public String getDescription() {
return beverage.getDescription() + ", Whip";
}
@Override
public double cost() {
return 0.10 + beverage.cost();
}
}
public class DecoratorPatternDemo {
public static void main(String[] args) {
Beverage beverage = new Espresso();
System.out.println(beverage.getDescription() + " $" + beverage.cost());
beverage = new Mocha(beverage);
beverage = new Whip(beverage);
System.out.println(beverage.getDescription() + " $" + beverage.cost());
}
}
四、单例模式(Singleton Pattern)
单例模式确保一个类只有一个实例,并提供一个全局访问点。
单例模式常用于需要全局唯一实例的场景,如配置管理类、日志类等。
示例代码:
package cn.juwatech.designpatterns.singleton;
public class Singleton {
private static Singleton uniqueInstance;
private Singleton() {}
public static synchronized Singleton getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
public void showMessage() {
System.out.println("Hello, I am a Singleton!");
}
public static void main(String[] args) {
Singleton singleton = Singleton.getInstance();
singleton.showMessage();
}
}
五、总结
设计模式提供了解决软件设计中常见问题的成熟方案。在《Head First设计模式》一书中,策略模式、观察者模式、装饰者模式和单例模式等典型设计模式通过生动的示例和详细的解释,帮助读者更好地理解和应用这些模式。希望通过本文的解析和案例分析,大家能更好地掌握这些设计模式,在实际开发中灵活运用,提高代码的可维护性和扩展性。