眼镜东莞网站建设,重庆市项目经理在建查询,redis 密码 wordpress,公司网站建设费用科目设计模式#xff08;Design Patterns#xff09;是软件开发中的宝贵经验总结#xff0c;提供了解决常见设计问题的模板和最佳实践。在Java开发中#xff0c;设计模式尤为重要#xff0c;因为它们能够提高代码的可维护性、可扩展性和可重用性。本篇博客将详细介绍几种常见的…设计模式Design Patterns是软件开发中的宝贵经验总结提供了解决常见设计问题的模板和最佳实践。在Java开发中设计模式尤为重要因为它们能够提高代码的可维护性、可扩展性和可重用性。本篇博客将详细介绍几种常见的设计模式帮助读者掌握如何在Java开发中应用这些模式。
什么是设计模式
设计模式是软件设计中反复出现的解决方案。它们不是具体的代码而是关于如何解决某一类型问题的一般性描述。设计模式通常分为三大类
创建型模式关注对象的创建方式。结构型模式关注类和对象的组合。行为型模式关注类和对象之间的交互。
创建型模式
单例模式Singleton Pattern
单例模式确保一个类只有一个实例并提供一个全局访问点。单例模式在需要控制资源的唯一性时非常有用例如数据库连接、线程池等。
public class Singleton {private static Singleton instance;private Singleton() {// 私有构造函数防止外部实例化}public static Singleton getInstance() {if (instance null) {instance new Singleton();}return instance;}
}优点
控制实例数量节省资源。提供全局访问点。
缺点
多线程环境下需要考虑同步问题。可能违背单一职责原则因为类既要管理实例的创建又要执行其他任务。
工厂模式Factory Pattern
工厂模式通过定义一个创建对象的接口来实现对象的实例化而不是直接通过new操作符。这样可以使得创建过程与使用过程分离。
interface Shape {void draw();
}class Circle implements Shape {Overridepublic void draw() {System.out.println(Drawing a Circle);}
}class Square implements Shape {Overridepublic void draw() {System.out.println(Drawing a Square);}
}class ShapeFactory {public Shape getShape(String shapeType) {if (shapeType null) {return null;}if (shapeType.equalsIgnoreCase(CIRCLE)) {return new Circle();} else if (shapeType.equalsIgnoreCase(SQUARE)) {return new Square();}return null;}
}优点
封装创建逻辑代码更简洁。易于扩展增加新类型无需修改现有代码。
缺点
增加了系统的复杂性需要更多的类和接口。
结构型模式
适配器模式Adapter Pattern
适配器模式将一个类的接口转换成客户端期望的另一个接口使得原本由于接口不兼容而不能一起工作的类可以协同工作。
interface MediaPlayer {void play(String audioType, String fileName);
}class AudioPlayer implements MediaPlayer {Overridepublic void play(String audioType, String fileName) {if (audioType.equalsIgnoreCase(mp3)) {System.out.println(Playing mp3 file. Name: fileName);}}
}interface AdvancedMediaPlayer {void playVlc(String fileName);void playMp4(String fileName);
}class VlcPlayer implements AdvancedMediaPlayer {Overridepublic void playVlc(String fileName) {System.out.println(Playing vlc file. Name: fileName);}Overridepublic void playMp4(String fileName) {// do nothing}
}class Mp4Player implements AdvancedMediaPlayer {Overridepublic void playVlc(String fileName) {// do nothing}Overridepublic void playMp4(String fileName) {System.out.println(Playing mp4 file. Name: fileName);}
}class MediaAdapter implements MediaPlayer {AdvancedMediaPlayer advancedMusicPlayer;public MediaAdapter(String audioType) {if (audioType.equalsIgnoreCase(vlc)) {advancedMusicPlayer new VlcPlayer();} else if (audioType.equalsIgnoreCase(mp4)) {advancedMusicPlayer new Mp4Player();}}Overridepublic void play(String audioType, String fileName) {if (audioType.equalsIgnoreCase(vlc)) {advancedMusicPlayer.playVlc(fileName);} else if (audioType.equalsIgnoreCase(mp4)) {advancedMusicPlayer.playMp4(fileName);}}
}class AudioPlayerAdapter implements MediaPlayer {MediaAdapter mediaAdapter;Overridepublic void play(String audioType, String fileName) {if (audioType.equalsIgnoreCase(mp3)) {System.out.println(Playing mp3 file. Name: fileName);} else if (audioType.equalsIgnoreCase(vlc) || audioType.equalsIgnoreCase(mp4)) {mediaAdapter new MediaAdapter(audioType);mediaAdapter.play(audioType, fileName);} else {System.out.println(Invalid media. audioType format not supported);}}
}优点
解耦客户端与服务端接口。增强代码的复用性。
缺点
增加代码复杂性。可能导致过多的适配器类。
装饰者模式Decorator Pattern
装饰者模式通过将对象放入包含行为的特殊封装对象中来动态地扩展对象的功能。
interface Shape {void draw();
}class Rectangle implements Shape {Overridepublic void draw() {System.out.println(Shape: Rectangle);}
}abstract class ShapeDecorator implements Shape {protected Shape decoratedShape;public ShapeDecorator(Shape decoratedShape) {this.decoratedShape decoratedShape;}public void draw() {decoratedShape.draw();}
}class RedShapeDecorator extends ShapeDecorator {public RedShapeDecorator(Shape decoratedShape) {super(decoratedShape);}Overridepublic void draw() {decoratedShape.draw();setRedBorder(decoratedShape);}private void setRedBorder(Shape decoratedShape) {System.out.println(Border Color: Red);}
}public class DecoratorPatternDemo {public static void main(String[] args) {Shape rectangle new Rectangle();Shape redRectangle new RedShapeDecorator(new Rectangle());System.out.println(Rectangle with normal border);rectangle.draw();System.out.println(\nRectangle with red border);redRectangle.draw();}
}优点
动态扩展对象功能。避免使用继承扩展类功能。
缺点
增加了许多小对象复杂度提高。不容易调试。
行为型模式
策略模式Strategy Pattern
策略模式定义了一系列算法并将每个算法封装起来使它们可以相互替换。策略模式让算法独立于使用它的客户端。
interface Strategy {int doOperation(int num1, int num2);
}class OperationAdd implements Strategy {Overridepublic int doOperation(int num1, int num2) {return num1 num2;}
}class OperationSubtract implements Strategy {Overridepublic int doOperation(int num1, int num2) {return num1 - num2;}
}class OperationMultiply implements Strategy {Overridepublic int doOperation(int num1, int num2) {return num1 * num2;}
}class Context {private Strategy strategy;public Context(Strategy strategy) {this.strategy strategy;}public int executeStrategy(int num1, int num2) {return strategy.doOperation(num1, num2);}
}public class StrategyPatternDemo {public static void main(String[] args) {Context context new Context(new OperationAdd());System.out.println(10 5 context.executeStrategy(10, 5));context new Context(new OperationSubtract());System.out.println(10 - 5 context.executeStrategy(10, 5));context new Context(new OperationMultiply());System.out.println(10 * 5 context.executeStrategy(10, 5));}
}优点
算法可自由切换。避免使用多重条件判断语句。提高算法的扩展性。
缺点
客户端必须知道所有策略类并自行决定使用哪一个策略类。策略模式会增加系统中类的数量。
观察者模式Observer Pattern
观察者模式定义了对象间的一对多依赖关系当一个对象改变状态时其所有依赖者都会收到通知并自动更新。
import java.util.ArrayList;
import java.util.List;class Subject {private ListObserver observers new ArrayList();private int state;public int getState() {return state;}public void setState(int