设计模式概述
设计模式是一种在软件开发中解决特定问题的通用方案。它们不是可以直接转化为代码的类或方法,而是对于如何构造软件组件的抽象描述。在Java开发中,了解并应用设计模式可以显著提高代码的可维护性、可扩展性和可读性。
实际项目中的设计模式应用
在实际项目中,不同的设计模式可以帮助我们解决不同的设计问题。本文将结合一些常见的设计模式,通过案例和代码示例展示如何在Java项目中应用这些模式。
1. 单例模式(Singleton Pattern)
应用场景
确保一个类只有一个实例,并提供一个全局访问点。适用于资源管理类,如数据库连接、日志对象等。
实现代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| public class DatabaseConnection { private static DatabaseConnection instance;
private DatabaseConnection() { }
public static synchronized DatabaseConnection getInstance() { if (instance == null) { instance = new DatabaseConnection(); } return instance; } }
|
使用示例
1 2 3 4 5 6
| public class Application { public static void main(String[] args) { DatabaseConnection connection = DatabaseConnection.getInstance(); } }
|
2. 工厂模式(Factory Pattern)
应用场景
用于创建对象的实例,而不需要在代码中显式指定对象的类。适合于复杂对象的创建过程。
实现代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| public interface Shape { void draw(); }
public class Circle implements Shape { public void draw() { System.out.println("Drawing a Circle"); } }
public class Rectangle implements Shape { public void draw() { System.out.println("Drawing a Rectangle"); } }
public class ShapeFactory { public static Shape getShape(String shapeType) { if ("CIRCLE".equalsIgnoreCase(shapeType)) { return new Circle(); } else if ("RECTANGLE".equalsIgnoreCase(shapeType)) { return new Rectangle(); } return null; } }
|
使用示例
1 2 3 4 5 6 7 8 9
| public class FactoryPatternDemo { public static void main(String[] args) { Shape shape1 = ShapeFactory.getShape("CIRCLE"); shape1.draw();
Shape shape2 = ShapeFactory.getShape("RECTANGLE"); shape2.draw(); } }
|
3. 观察者模式(Observer Pattern)
应用场景
当一个对象状态发生变化时,所有依赖于它的对象都得到通知并自动更新。适用于事件处理系统,如用户界面变化、消息推送等。
实现代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| import java.util.ArrayList; import java.util.List;
interface Observer { void update(String message); }
class ConcreteObserver implements Observer { private String name;
public ConcreteObserver(String name) { this.name = name; }
@Override public void update(String message) { System.out.println(name + " received message: " + message); } }
class Subject { private List<Observer> observers = new ArrayList<>();
public void addObserver(Observer observer) { observers.add(observer); }
public void notifyObservers(String message) { for (Observer observer : observers) { observer.update(message); } } }
|
使用示例
1 2 3 4 5 6 7 8 9 10 11 12 13
| public class ObserverPatternDemo { public static void main(String[] args) { Subject subject = new Subject();
Observer observer1 = new ConcreteObserver("Observer 1"); Observer observer2 = new ConcreteObserver("Observer 2");
subject.addObserver(observer1); subject.addObserver(observer2);
subject.notifyObservers("Hello Observers!"); } }
|
4. 策略模式(Strategy Pattern)
应用场景
定义一系列算法,并将每一个算法封装起来,使它们可以互换。适用于需要选择算法的情况,如支付方式、排序算法等。
实现代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| interface PaymentStrategy { void pay(int amount); }
class CreditCardPayment implements PaymentStrategy { @Override public void pay(int amount) { System.out.println("Paid " + amount + " using Credit Card."); } }
class PayPalPayment implements PaymentStrategy { @Override public void pay(int amount) { System.out.println("Paid " + amount + " using PayPal."); } }
class ShoppingCart { private PaymentStrategy paymentStrategy;
public void setPaymentStrategy(PaymentStrategy paymentStrategy) { this.paymentStrategy = paymentStrategy; }
public void checkout(int amount) { paymentStrategy.pay(amount); } }
|
使用示例
1 2 3 4 5 6 7 8 9 10 11
| public class StrategyPatternDemo { public static void main(String[] args) { ShoppingCart cart = new ShoppingCart();
cart.setPaymentStrategy(new CreditCardPayment()); cart.checkout(100);
cart.setPaymentStrategy(new PayPalPayment()); cart.checkout(200); } }
|
5. 装饰者模式(Decorator Pattern)
应用场景
在不改变对象结构的情况下,动态地为一个对象添加额外的职责。适用于功能扩展,如图形界面的组件、输入流等。
实现代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| interface Coffee { String getDescription(); double cost(); }
class SimpleCoffee implements Coffee { @Override public String getDescription() { return "Simple Coffee"; }
@Override public double cost() { return 5.0; } }
abstract class CoffeeDecorator implements Coffee { protected Coffee coffee;
public CoffeeDecorator(Coffee coffee) { this.coffee = coffee; } }
class MilkDecorator extends CoffeeDecorator { public MilkDecorator(Coffee coffee) { super(coffee); }
@Override public String getDescription() { return coffee.getDescription() + ", Milk"; }
@Override public double cost() { return coffee.cost() + 1.5; } }
class SugarDecorator extends CoffeeDecorator { public SugarDecorator(Coffee coffee) { super(coffee); }
@Override public String getDescription() { return coffee.getDescription() + ", Sugar"; }
@Override public double cost() { return coffee.cost() + 0.5; } }
|
使用示例
public class DecoratorPatternDemo {
public static void main(String[] args) {
Coffee coffee = new SimpleCoffee();
System.out.println(coffee.getDescription() + " Cost: " + coffee.cost());
Coffee milkCoffee = new MilkDecorator(coffee);
System.out.println(milkCoffee.getDescription() + " Cost: " + milkCoffee.cost());
Coffee sugarMilkCoffee = new SugarDecorator(milkCoffee);
System.out.println(sugarMilkCoffee.getDescription