JAVA设计模式
发布人:shili8
发布时间:2025-01-01 19:54
阅读次数:0
**Java 设计模式**
设计模式是一套被反复使用、多数人知晓、经过时间检验的解决方案。它提供了一种模板或框架,让我们可以用更高效、更标准化的方式来解决一些常见的问题。
在 Java 中,设计模式有很多种类,每一种都解决了特定的问题。在本文中,我们将介绍一些最常用的设计模式及其应用。
###1. 单例模式**定义:**
Singleton(单例)模式是一种创建型模式,它保证一个类只有一个实例,并提供全局访问点。
**实现:**
javapublic class Singleton {
// 私有构造函数,防止外部直接new private Singleton() {}
// 静态变量,保存唯一的实例 private static Singleton instance = null;
// 公共方法,返回唯一的实例 public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
public void doSomething() {
System.out.println("Doing something...");
}
}
**注释:**
* 私有构造函数防止外部直接new实例。
* 静态变量保存唯一的实例。
* 公共方法返回唯一的实例。
###2. 工厂模式**定义:**
Factory(工厂)模式是一种创建型模式,它提供了一个用于创建对象的接口,而不需要暴露具体类名。
**实现:**
javapublic abstract class Animal {
public abstract void sound();
}
public class Dog extends Animal {
@Override public void sound() {
System.out.println("Woof!");
}
}
public class Cat extends Animal {
@Override public void sound() {
System.out.println("Meow!");
}
}
public class AnimalFactory {
public static Animal createAnimal(String type) {
if (type.equals("dog")) {
return new Dog();
} else if (type.equals("cat")) {
return new Cat();
} else {
throw new RuntimeException("Invalid animal type");
}
}
public static void main(String[] args) {
Animal dog = createAnimal("dog");
Animal cat = createAnimal("cat");
dog.sound(); // Woof!
cat.sound(); // Meow!
}
}
**注释:**
* 抽象类Animal定义了一个抽象方法sound()。
* 具体类Dog和Cat继承了Animal类,并实现了sound()方法。
* 工厂类AnimalFactory提供了一个用于创建对象的接口。
###3. 观察者模式**定义:**
Observer(观察者)模式是一种行为型模式,它定义了一对多关系,使得一个对象可以随时通知其他对象关于状态变化。
**实现:**
javapublic interface Observer {
void update(String message);
}
public class WeatherStation implements Observer {
private String weather;
public void setWeather(String weather) {
this.weather = weather;
notifyObservers();
}
@Override public void update(String message) {
System.out.println("Received weather update: " + message);
}
}
public class ForecastDisplay implements Observer {
@Override public void update(String message) {
System.out.println("Forecast updated: " + message);
}
}
public class WeatherStationMain {
public static void main(String[] args) {
WeatherStation station = new WeatherStation();
ForecastDisplay display = new ForecastDisplay();
station.addObserver(display);
station.setWeather("Sunny");
station.setWeather("Rainy");
}
}
**注释:**
* 观察者接口定义了一个update()方法。
* 被观察者类WeatherStation维护了一组观察者,并提供了addObserver()和notifyObservers()方法。
* 具体的观察者类ForecastDisplay实现了update()方法。
###4. 适配器模式**定义:**
Adapter(适配器)模式是一种结构型模式,它使得两个不兼容的接口能够一起工作。
**实现:**
javapublic interface Duck {
void quack();
}
public class Turkey {
public void gobble() {
System.out.println("Gobble!");
}
}
public class TurkeyAdapter implements Duck {
private Turkey turkey;
public TurkeyAdapter(Turkey turkey) {
this.turkey = turkey;
}
@Override public void quack() {
turkey.gobble();
}
}
public class Main {
public static void main(String[] args) {
Turkey turkey = new Turkey();
Duck duck = new TurkeyAdapter(turkey);
duck.quack(); // Gobble!
}
}
**注释:**
* 鸭子接口定义了一个quack()方法。
* 火鸡类定义了一个gobble()方法。
* 适配器类TurkeyAdapter实现了鸭子接口,并将火鸡的行为适配到鸭子的接口中。
###5. 组合模式**定义:**
Composite(组合)模式是一种结构型模式,它允许你将对象组合成树状结构,从而使得客户端代码可以忽略不同对象间的差异。
**实现:**
javapublic interface Component {
void operation();
}
public class Leaf implements Component {
@Override public void operation() {
System.out.println("Leaf operation");
}
}
public class Composite implements Component {
private List children = new ArrayList<>();
public void add(Component component) {
children.add(component);
}
@Override public void operation() {
for (Component child : children) {
child.operation();
}
}
}
public class Main {
public static void main(String[] args) {
Composite composite = new Composite();
Leaf leaf1 = new Leaf();
Leaf leaf2 = new Leaf();
composite.add(leaf1);
composite.add(leaf2);
composite.operation(); // Leaf operation, Leaf operation }
}
**注释:**
* 组件接口定义了一个operation()方法。
* 叶类Leaf实现了组件接口,并提供了叶的行为。
* 组合类Composite实现了组件接口,并维护了一组子组件。
###6. 装饰器模式**定义:**
Decorator(装饰器)模式是一种结构型模式,它允许你动态地将责任添加到对象中,而无需通过继承来创建一个新的类。
**实现:**
javapublic interface Component {
void operation();
}
public class ConcreteComponent implements Component {
@Override public void operation() {
System.out.println("Concrete component");
}
}
public abstract class Decorator implements Component {
protected Component component;
public Decorator(Component component) {
this.component = component;
}
@Override public void operation() {
component.operation();
}
}
public class ConcreteDecorator extends Decorator {
public ConcreteDecorator(Component component) {
super(component);
}
@Override public void operation() {
System.out.println("Concrete decorator");
super.operation();
}
}
public class Main {
public static void main(String[] args) {
Component component = new ConcreteComponent();
Decorator decorator = new ConcreteDecorator(component);
decorator.operation(); // Concrete decorator, Concrete component }
}
**注释:**
* 组件接口定义了一个operation()方法。
*具体的组件类ConcreteComponent实现了组件接口,并提供了叶的行为。
*装饰器类Decorator实现了组件接口,并维护了一组子组件。
*具体的装饰器类ConcreteDecorator继承了装饰器类,并添加了新的责任。
###7. 外观模式**定义:**
Facade(外观)模式是一种结构型模式,它提供了一个单一的接口,用于访问一个复杂的子系统。
**实现:**
javapublic interface SubSystem {
void operation();
}
public class ConcreteSubSystem1 implements SubSystem {
@Override public void operation() {
System.out.println("Concrete sub system1");
}
}
public class ConcreteSubSystem2 implements SubSystem {
@Override public void operation() {
System.out.println("Concrete sub system2");
}
}
public class Facade {
private List subsystems = new ArrayList<>();
public void add(SubSystem subsystem) {
subsystems.add(subsystem);
}
public void operation() {
for (SubSystem subsystem : subsystems) {
subsystem.operation();
}
}
}
public class Main {
public static void main(String[] args) {
Facade facade = new Facade();
facade.add(new ConcreteSubSystem1());
facade.add(new ConcreteSubSystem2());
facade.operation(); // Concrete sub system1, Concrete sub system2 }
}
**注释:**
* 子系统接口定义了一个operation()方法。
*具体的子系统

