设计模式面试题总结:10个高频考点与答案解析
1. 单例模式
问题:请解释单例模式,并给出一个Java实现。
答案解析:单例模式确保一个类只有一个实例,并提供一个全局访问点。在Java中,可以使用“双重检查锁定”来实现线程安全的单例。
java
public class Singleton {
private static volatile Singleton instance;
private Singleton() {
// 私有构造函数
}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
2. 工厂模式
问题:请解释工厂模式,并给出一个Python实现。
答案解析:工厂模式是一种创建对象的模式,它提供了一种封装来创建对象的方式,从而隐藏了对象的创建逻辑。
python
class Car:
def drive(self):
pass
class Toyota(Car):
def drive(self):
print("Driving Toyota")
class Ford(Car):
def drive(self):
print("Driving Ford")
class CarFactory:
def get_car(self, car_type):
if car_type == "toyota":
return Toyota()
elif car_type == "ford":
return Ford()
3. 观察者模式
问题:请解释观察者模式,并给出一个Java实现。
答案解析:观察者模式是一种发布-订阅模型,其中主题发布状态更改,观察者接收通知并更新自己。
java
import java.util.ArrayList;
import java.util.List;
interface Observer {
void update(String message);
}
interface Subject {
void register(Observer observer);
void remove(Observer observer);
void notify(String message);
}
class ConcreteSubject implements Subject {
private List observers = new ArrayList();
@Override
public void register(Observer observer) {
observers.add(observer);
}
@Override
public void remove(Observer observer) {
observers.remove(observer);
}
@Override
public void notify(String message) {
for (Observer observer : observers) {
observer.update(message);
}
}
}
class ConcreteObserver implements Observer {
@Override
public void update(String message) {
System.out.println("Received message: " + message);
}
}
4. 适配器模式
问题:请解释适配器模式,并给出一个Java实现。
答案解析:适配器模式将一个类的接口转换为另一个类的接口,以满足客户端的需求。
java
interface Target {
void request();
}
class Adaptee {
void specificRequest() {
System.out.println("Called specificRequest()");
}
}
class Adapter implements Target {
private Adaptee adaptee;
public Adapter(Adaptee adaptee) {
this.adaptee = adaptee;
}
@Override
public void request() {
adaptee.specificRequest();
}
}
5. 策略模式
问题:请解释策略模式,并给出一个Java实现。
答案解析:策略模式定义了算法族,并将它们封装起来,使它们可以相互替换。
java
interface Strategy {
void execute();
}
class StrategyA implements Strategy {
@Override
public void execute() {
System.out.println("Executing Strategy A");
}
}
class StrategyB implements Strategy {
@Override
public void execute() {
System.out.println("Executing Strategy B");
}
}
class Context {
private Strategy strategy;
public Context(Strategy strategy) {
this.strategy = strategy;
}
public void executeStrategy() {
strategy.execute();
}
}
6. 装饰器模式
问题:请解释装饰器模式,并给出一个Java实现。
答案解析:装饰器模式提供了一种动态地为对象添加职责的方式。
java
interface Component {
void operation();
}
class ConcreteComponent implements Component {
@Override
public void operation() {
System.out.println("Executing operation in ConcreteComponent");
}
}
class Decorator implements Component {
private Component component;
public Decorator(Component component) {
this.component = component;
}
@Override
public void operation() {
System.out.println("Executing operation in Decorator before concrete component");
if (component != null) {
component.operation();
}
System.out.println("Executing operation in Decorator after concrete component");
}
}
7. 建造者模式
问题:请解释建造者模式,并给出一个Java实现。
答案解析:建造者模式提供了一种构建复杂对象的方式,它允许用户逐步构建对象。
java
class Builder {
private String part1;
private String part2;
public Builder part1(String part1) {
this.part1 = part1;
return this;
}
public Builder part2(String part2) {
this.part2 = part2;
return this;
}
public Product build() {
return new Product(this);
}
}
class Product {
private String part1;
private String part2;
private Product(Builder builder) {
this.part1 = builder.part1;
this.part2 = builder.part2;
}
}
8. 原型模式
问题:请解释原型模式,并给出一个Java实现。
答案解析:原型模式提供了一种创建对象的最佳方式,即基于已创建的对象进行复制。
java
import java.util.Cloneable;
class Prototype implements Cloneable {
private String part;
public String getPart() {
return part;
}
public void setPart(String part) {
this.part = part;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class Main {
public static void main(String[] args) {
Prototype original = new Prototype();
original.setPart("Original");
Prototype clone = (Prototype) original.clone();
clone.setPart("Clone");
System.out.println(original.getPart()); // Outputss: Original
System.out.println(clone.getPart()); // Outputs: Clone
}
}
9. 代理模式
问题:请解释代理模式,并给出一个Java实现。
答案解析:代理模式为另一个对象提供一个代理,以控制对原对象的访问。
java
interface Subject {
void request();
}
class RealSubject implements Subject {
@Override
public void request() {
System.out.println("Request in RealSubject");
}
}
class ProxySubject implements Subject {
private RealSubject realSubject;
public ProxySubject(RealSubject realSubject) {
this.realSubject = realSubject;
}
@Override
public void request() {
System.out.println("Before request in RealSubject");
if (realSubject != null) {
realSubject.request();
}
System.out.println("After request in RealSubject");
}
}
10. 模板方法模式
问题:请解释模板方法模式,并给出一个Java实现。
答案解析:模板方法模式定义了一个操作中的算法骨架,并允许子类在不改变算法结构的情况下重写某些步骤。
java
abstract class TemplateMethod {
public final void templateMethod() {
basicOperation1();
basicOperation2();
hook1();
basicOperation3();
hook2();
}
protected abstract void hook1();
protected abstract void hook2();
protected void basicOperation1() {
System.out.println("Executing basicOperation1");
}
protected void basicOperation2() {
System.out.println("Executing basicOperation2");
}
protected void basicOperation3() {
System.out.println("Executing basicOperation3");
}
}
class ConcreteTemplateMethod extends TemplateMethod {
@Override
protected void hook1() {
System.out.println("Executing hook1 in ConcreteTemplateMethod");
}
@Override
protected void hook2() {
System.out.println("Executing hook2 in ConcreteTemplateMethod");
}
}
以上是10个设计模式的高频考点及其答案解析。在面试中,这些模式通常用于评估应聘者的编程和设计能力。通过理解这些模式,应聘者可以更好地解决设计问题,并编写出更灵活、可维护的代码。
