面试题答案
一键面试1. 使用策略模式实现
首先定义一个接口来表示数据交互的策略:
// 定义数据交互策略接口
interface DataInteractionStrategy {
// 定义数据交互方法,参数和返回值根据实际需求调整
interact(data: any): Promise<any>;
}
然后为每个模块实现具体的策略类:
// 模块A的数据交互策略类
class ModuleAInteractionStrategy implements DataInteractionStrategy {
async interact(data: any): Promise<any> {
// 模块A特有的数据交互逻辑,例如添加特定的请求头
const response = await fetch('/api/moduleA', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Module-Specific-Header': 'ModuleA'
},
body: JSON.stringify(data)
});
return response.json();
}
}
// 模块B的数据交互策略类
class ModuleBInteractionStrategy implements DataInteractionStrategy {
async interact(data: any): Promise<any> {
// 模块B特有的数据交互逻辑,例如处理不同的响应格式
const response = await fetch('/api/moduleB', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
const text = await response.text();
// 假设模块B的响应是特定格式,需要特殊处理
return { customResponse: text };
}
}
接着,创建一个上下文类,用于持有具体的策略并执行交互:
// 数据交互上下文类
class DataInteractionContext {
private strategy: DataInteractionStrategy;
constructor(strategy: DataInteractionStrategy) {
this.strategy = strategy;
}
async interactWithServer(data: any): Promise<any> {
return this.strategy.interact(data);
}
}
在实际使用中:
// 使用模块A的策略
const moduleAContext = new DataInteractionContext(new ModuleAInteractionStrategy());
moduleAContext.interactWithServer({ key: 'value' }).then(result => {
console.log('Module A result:', result);
});
// 使用模块B的策略
const moduleBContext = new DataInteractionContext(new ModuleBInteractionStrategy());
moduleBContext.interactWithServer({ key: 'value' }).then(result => {
console.log('Module B result:', result);
});
2. 策略模式在这种场景下的优势
- 可维护性高:每个模块的数据交互逻辑封装在各自的策略类中。如果某个模块的交互逻辑需要修改,只需要修改对应的策略类,而不会影响其他模块的代码。例如,如果模块A的后端接口地址发生变化,只需要在
ModuleAInteractionStrategy
类中修改fetch
的地址即可。 - 可扩展性强:当有新的模块需要添加数据交互逻辑时,只需要创建一个新的策略类并实现
DataInteractionStrategy
接口,然后在需要的地方创建对应的上下文对象来使用该策略。比如新增模块C,只需要创建ModuleCInteractionStrategy
类并按照上述方式使用。 - 代码复用性好:虽然每个模块的数据交互逻辑有细微差别,但整体的数据交互框架(如
DataInteractionContext
和DataInteractionStrategy
接口)是复用的。例如不同模块都使用fetch
进行网络请求,请求方法、处理响应等基本逻辑在策略接口和上下文类中可以统一管理和复用。