设计模式的类型
- 结构型模式 识别组件之间的简单关系
- 创建型模式 根据合适方法创建对象
- 行为型模式 识别对象间交互模式
一. 结构型模式(Structural Patterns)
代理模式
要点
Real Subject:真实对象Proxy:代理对象Subject接口:Real Subject 和 Proxy都需要实现的接口,这样Proxy才能被当成Real Subject的“替身”使用
// 定义一个接口 Subject,包含了被代理对象和代理对象共同的方法
class Subject {
request() {
throw new Error('This method must be overridden');
}
}
// 定义一个具体的实现类 RealSubject
class RealSubject extends Subject {
request() {
console.log('RealSubject: 处理请求');
}
}
// 定义一个代理类 Proxy
class Proxy extends Subject {
constructor() {
super();
this.realSubject = new RealSubject();
}
request() {
// 在执行请求之前或之后,代理类可以执行一些额外的操作
console.log('Proxy: 在请求之前的额外操作');
// 调用被代理对象的方法
this.realSubject.request();
console.log('Proxy: 在请求之后的额外操作');
}
}
// 使用代理对象进行请求
const proxy = new Proxy();
proxy.request();
当我们创建一个代理对象 proxy 并调用它的 request 方法时,代理对象会在执行请求之前和之后分别打印出一些额外的操作,然后委托给实际的被代理对象 RealSubject 来处理请求。
这就是代理模式的基本实现。通过代理对象,我们可以控制对实际对象的访问并在访问前后执行额外的操作,例如权限验证、缓存、延迟加载等。
二. 创建型模式(Creational Patterns)
工厂可以看成是一个制造其他对象的对象,制造出的对象也会随着传入工厂对象参数的不同而有所区别。
什么场景适合使用
当构造函数过多不方便管理,且需要创建的对象之间存在某些关联
// 定义一个基类 Animal
class Animal {
constructor(name) {
this.name = name;
}
speak() {
throw new Error('This method must be overridden');
}
}
// 定义具体的子类 Dog
class Dog extends Animal {
speak() {
return 'Woof!';
}
}
// 定义具体的子类 Cat
class Cat extends Animal {
speak() {
return 'Meow!';
}
}
// 定义一个动物工厂类 AnimalFactory
class AnimalFactory {
createAnimal(type, name) {
switch (type) {
case 'dog':
return new Dog(name);
case 'cat':
return new Cat(name);
default:
throw new Error('Invalid animal type');
}
}
}
// 使用工厂创建对象
const factory = new AnimalFactory();
const dog = factory.createAnimal('dog', 'Buddy');
console.log(dog.name); // 输出: Buddy
console.log(dog.speak()); // 输出: Woof!
const cat = factory.createAnimal('cat', 'Kitty');
console.log(cat.name); // 输出: Kitty
console.log(cat.speak()); // 输出: Meow!
定义了一个动物工厂类 AnimalFactory,它具有一个 createAnimal 方法,根据传入的动物类型和名称来实例化相应的动物对象。
在示例中,我们首先通过工厂创建了一只名为 "Buddy" 的狗对象,并打印了它的名称和叫声。然后,我们创建了一只名为 "Kitty" 的猫对象,并同样打印了它的名称和叫声
总结:工厂模式的优点是可以将对象的创建逻辑封装起来,从而更好地组织和管理代码。通过工厂方法,我们可以轻松地添加新的子类,而无需修改使用工厂的代码。这样提高了代码的可维护性和扩展性。
如果你觉得不错,请给我点赞呦~