java常见设计模式及实现,java常见设计模式及实现方法

2025-03-09 17:00:22作者:饭克斯

在软件开发中,设计模式作为一种优秀的代码复用方式,在Java编程中尤为重要。设计模式为程序员提供了可重用的解决方案,满足了不同场景下的需求。本篇文章将介绍几种常见的Java设计模式及其实现方法。

java常见设计模式及实现,java常见设计模式及实现方法

一、单例模式

单例模式确保一个类只有一个实例,并提供一个全局访问点。实现单例模式的常见方法有懒汉式和饿汉式两种。

懒汉式实现:

public class Singleton { private static Singleton instance; private Singleton() {} public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }

饿汉式实现:

public class Singleton { private static final Singleton INSTANCE = new Singleton(); private Singleton() {} public static Singleton getInstance() { return INSTANCE; } }

二、工厂模式

工厂模式用于创建对象,提供一种创建对象的接口,而让子类决定实例化哪一个类。工厂模式分为简单工厂、工厂方法和抽象工厂三种。

简单工厂实现:

public class ShapeFactory { public static Shape getShape(String shapeType) { if (shapeType == null) { return null; } if (CIRCLE.equalsIgnoreCase(shapeType)) { return new Circle(); } else if (RECTANGLE.equalsIgnoreCase(shapeType)) { return new Rectangle(); } return null; } } 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 interface Strategy { int doOperation(int num1, int num2); } public class OperationAdd implements Strategy { public int doOperation(int num1, int num2) { return num1 + num2; } } public class OperationSubtract implements Strategy { public int doOperation(int num1, int num2) { return num1 num2; } } public class Context { private Strategy strategy; public Context(Strategy strategy) { this.strategy = strategy; } public int executeStrategy(int num1, int num2) { return strategy.doOperation(num1, num2); } }

四、观察者模式

观察者模式定义了一种一对多的依赖关系,使得当对象状态改变时,所有依赖于它的对象都会得到通知并自动更新。

观察者模式实现:

import java.util.ArrayList; import java.util.List; public interface Subject { void attach(Observer observer); void detach(Observer observer); void notifyObservers(); } public interface Observer { void update(); } public class ConcreteSubject implements Subject { private List observers = new ArrayList<>(); private String state; public void attach(Observer observer) { observers.add(observer); } public void detach(Observer observer) { observers.remove(observer); } public void notifyObservers() { for (Observer observer : observers) { observer.update(); } } public void setState(String state) { this.state = state; notifyObservers(); } } public class ConcreteObserver implements Observer { private String name; public ConcreteObserver(String name) { this.name = name; } public void update() { System.out.println(Observer + name + updated.); } }

设计模式是程序设计中的一项重要原则,掌握Java的常见设计模式能够帮助开发者更高效地进行软件开发和维护。本文简要介绍了单例模式、工厂模式、策略模式和观察者模式的基本知识及其实现方法,希望能为广大Java开发者提供参考和帮助。在实际项目中,灵活应用设计模式,可以提升代码的可读性、可维护性和扩展性。

展开全文

热门推荐

相关攻略

猜你喜欢