说一说你用到了那些设计模式 - 面试宝典
【摘要】 作为一名软件架构师,我在项目开发过程中使用了多种设计模式来解决不同的问题。以下是我用到的一些常见设计模式:单例模式:用于确保一个类只有一个实例,并提供一个全局访问点。在多线程环境下,可以使用线程安全的单例模式。工厂模式:用于创建对象,隐藏具体实现细节,通过工厂类来创建对象,提供了一种扩展性好的解决方案。观察者模式:用于对象之间的一对多依赖关系,当一个对象的状态发生改变时,所有依赖它的对象都会...
作为一名软件架构师,我在项目开发过程中使用了多种设计模式来解决不同的问题。以下是我用到的一些常见设计模式:
- 单例模式:用于确保一个类只有一个实例,并提供一个全局访问点。在多线程环境下,可以使用线程安全的单例模式。
- 工厂模式:用于创建对象,隐藏具体实现细节,通过工厂类来创建对象,提供了一种扩展性好的解决方案。
- 观察者模式:用于对象之间的一对多依赖关系,当一个对象的状态发生改变时,所有依赖它的对象都会得到通知并自动更新。
- 策略模式:将不同的算法封装成独立的类,使得它们可以互相替换,提高了代码的灵活性和可维护性。
- 适配器模式:用于将一个类的接口转换成客户端所期望的另一种接口,使得原本不兼容的类可以一起工作。
- 模板方法模式:定义一个算法的骨架,将一些步骤的实现延迟到子类中,可以在不改变算法结构的情况下重新定义算法的某些步骤。
- 装饰者模式:动态地给一个对象添加额外的功能,是继承的一种替代方案,避免了继承链的臃肿。
- 建造者模式:用于创建复杂对象,将对象的构建过程和表示分离,使得同样的构建过程可以创建不同的表示。 以上只是我在实际项目中使用的一些设计模式,具体的选择和使用还要根据具体的场景和需求来确定。
下面是一些代码示例来说明我在项目中使用的设计模式:
- 单例模式:
javaCopy codepublic class Singleton {
private static Singleton instance;
private Singleton() {
// 私有化构造方法,避免外部实例化
}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
- 工厂模式:
javaCopy codepublic interface Shape {
void draw();
}
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Drawing a circle");
}
}
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Drawing a rectangle");
}
}
public class ShapeFactory {
public Shape createShape(String shapeType) {
if (shapeType.equalsIgnoreCase("circle")) {
return new Circle();
} else if (shapeType.equalsIgnoreCase("rectangle")) {
return new Rectangle();
}
return null;
}
}
- 观察者模式:
javaCopy codeimport java.util.ArrayList;
import java.util.List;
public interface Observer {
void update();
}
public class ConcreteObserver implements Observer {
@Override
public void update() {
System.out.println("Received notification");
}
}
public class Subject {
private List<Observer> observers = new ArrayList<>();
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();
}
}
}
以上是一些常见设计模式的简单示例,实际应用中还会结合具体的业务需求进行适当的扩展和灵活运用。
- 策略模式:
javaCopy codepublic interface PaymentStrategy {
void pay(double amount);
}
public class CreditCardPayment implements PaymentStrategy {
private String cardNumber;
private String expirationDate;
private String cvv;
public CreditCardPayment(String cardNumber, String expirationDate, String cvv) {
this.cardNumber = cardNumber;
this.expirationDate = expirationDate;
this.cvv = cvv;
}
@Override
public void pay(double amount) {
// 实现信用卡支付逻辑
}
}
public class CashPayment implements PaymentStrategy {
@Override
public void pay(double amount) {
// 实现现金支付逻辑
}
}
public class ShoppingCart {
private List<Item> items;
private PaymentStrategy paymentStrategy;
public void setPaymentStrategy(PaymentStrategy paymentStrategy) {
this.paymentStrategy = paymentStrategy;
}
public void addItem(Item item) {
items.add(item);
}
public void removeItem(Item item) {
items.remove(item);
}
public double calculateTotal() {
double total = 0;
// 计算购物车中商品的总价
return total;
}
public void pay() {
double amount = calculateTotal();
paymentStrategy.pay(amount);
}
}
- 适配器模式:
javaCopy codepublic interface MediaPlayer {
void play(String audioType, String fileName);
}
public interface AdvancedMediaPlayer {
void playVlc(String fileName);
void playMp4(String fileName);
}
public class VlcPlayer implements AdvancedMediaPlayer {
@Override
public void playVlc(String fileName) {
System.out.println("Playing vlc file: " + fileName);
}
@Override
public void playMp4(String fileName) {
// do nothing
}
}
public class Mp4Player implements AdvancedMediaPlayer {
@Override
public void playVlc(String fileName) {
// do nothing
}
@Override
public void playMp4(String fileName) {
System.out.println("Playing mp4 file: " + fileName);
}
}
public class MediaAdapter implements MediaPlayer {
private AdvancedMediaPlayer advancedMediaPlayer;
public MediaAdapter(String audioType) {
if (audioType.equalsIgnoreCase("vlc")) {
advancedMediaPlayer = new VlcPlayer();
} else if (audioType.equalsIgnoreCase("mp4")) {
advancedMediaPlayer = new Mp4Player();
}
}
@Override
public void play(String audioType, String fileName) {
if (audioType.equalsIgnoreCase("vlc")) {
advancedMediaPlayer.playVlc(fileName);
} else if (audioType.equalsIgnoreCase("mp4")) {
advancedMediaPlayer.playMp4(fileName);
}
}
}
public class AudioPlayer implements MediaPlayer {
private MediaAdapter mediaAdapter;
@Override
public void play(String audioType, String fileName) {
if (audioType.equalsIgnoreCase("mp3")) {
System.out.println("Playing mp3 file: " + fileName);
} else if (audioType.equalsIgnoreCase("vlc") || audioType.equalsIgnoreCase("mp4")) {
mediaAdapter = new MediaAdapter(audioType);
mediaAdapter.play(audioType, fileName);
} else {
System.out.println("Invalid media type");
}
}
}
以上是一些常见设计模式的代码示例,通过使用这些设计模式,可以提高代码的可维护性、扩展性和灵活性,使软件架构更加健壮和可靠。当然,在实际项目中,我们还需要根据具体需求进行灵活选择和调整。
6.装饰器模式:
javaCopy codepublic interface Shape {
void draw();
}
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Drawing a circle");
}
}
public abstract class ShapeDecorator implements Shape {
protected Shape decoratedShape;
public ShapeDecorator(Shape decoratedShape) {
this.decoratedShape = decoratedShape;
}
@Override
public void draw() {
decoratedShape.draw();
}
}
public class RedShapeDecorator extends ShapeDecorator {
public RedShapeDecorator(Shape decoratedShape) {
super(decoratedShape);
}
@Override
public void draw() {
decoratedShape.draw();
setRedBorder(decoratedShape);
}
private void setRedBorder(Shape decoratedShape) {
System.out.println("Setting red border for the shape");
}
}
7.模板方法模式:
javaCopy codepublic abstract class Game {
abstract void initialize();
abstract void startPlay();
abstract void endPlay();
public final void play() {
initialize();
startPlay();
endPlay();
}
}
public class Cricket extends Game {
@Override
void initialize() {
System.out.println("Cricket Game Initialized! Start playing.");
}
@Override
void startPlay() {
System.out.println("Cricket Game Started. Enjoy the game!");
}
@Override
void endPlay() {
System.out.println("Cricket Game Finished!");
}
}
public class Football extends Game {
@Override
void initialize() {
System.out.println("Football Game Initialized! Start playing.");
}
@Override
void startPlay() {
System.out.println("Football Game Started. Enjoy the game!");
}
@Override
void endPlay() {
System.out.println("Football Game Finished!");
}
}
8.责任链模式:
javaCopy codepublic abstract class Logger {
public static int INFO = 1;
public static int DEBUG = 2;
public static int ERROR = 3;
protected int level;
protected Logger nextLogger;
public void setNextLogger(Logger nextLogger) {
this.nextLogger = nextLogger;
}
public void logMessage(int level, String message) {
if (this.level <= level) {
write(message);
}
if (nextLogger != null) {
nextLogger.logMessage(level, message);
}
}
abstract protected void write(String message);
}
public class ConsoleLogger extends Logger {
public ConsoleLogger(int level) {
this.level = level;
}
@Override
protected void write(String message) {
System.out.println("Console Logger: " + message);
}
}
public class FileLogger extends Logger {
public FileLogger(int level) {
this.level = level;
}
@Override
protected void write(String message) {
System.out.println("File Logger: " + message);
}
}
public class ErrorLogger extends Logger {
public ErrorLogger(int level) {
this.level = level;
}
@Override
protected void write(String message) {
System.out.println("Error Logger: " + message);
}
}
以上是一些常见设计模式的代码示例,这些设计模式可以帮助我们解决不同的问题,提高代码的可维护性和复用性。在实际开发中,我们可以根据具体需求选择适合的设计模式来设计和组织代码。
【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
作者其他文章
皮牙子抓饭2023/08/23 01:41:271楼编辑删除举报