笔记-11-JavaScript设计模式
观察者模式(行为型):应用场景 订阅发布 (vue)
class PubSub {
constructor() {
this.handlers = {};
}
subscribe(event, handler) {
this.handlers[event] = this.handlers[event] || [];
this.handlers[event].push(handler);
}
publish(event, data) {
if (this.handlers[event]) {
this.handlers[event].forEach(handler => handler(data));
}
}
}
// 使用示例
const pubsub = new PubSub();
// 订阅者
const subscriber = (data) => {
console.log(`收到消息: ${data}`);
};
// 订阅 'message' 事件
pubsub.subscribe('message', subscriber);
// 发布 'message' 事件
pubsub.publish('message', 'Hello, world!');
单例模式(创建型):【一个页面只能弹出一个登录框,不能弹多个|后端数据不重复创建】
function Singleton(name) {
this.name = name;
if (!Singleton.instance) {
Singleton.instance = this;
}
return Singleton.instance;
}
const instance1 = new Singleton('Alice');
const instance2 = new Singleton('Bob');
console.log(instance1 === instance2); // true,因为instance1和instance2是同一个实例
-----------
class Singleton {
// 使用静态方法或属性来保存类的唯一实例
static instance = null;
// 私有化构造函数,防止外部实例化
constructor() {
if (Singleton.instance) {
return Singleton.instance;
}
// 初始化实例
this.value = Math.random(); // 示例属性
// 将当前实例保存为静态属性
Singleton.instance = this;
return this;
}
// 类的方法
getValue() {
return this.value;
}
}
// 尝试创建多个实例
const instance1 = new Singleton();
const instance2 = new Singleton();
console.log(instance1.getValue()); // 输出一个随机数
console.log(instance2.getValue()); // 输出与instance1相同的随机数,说明是同一个实例
console.log(instance1 === instance2); // 输出: true,说明instance1和instance2是同一个实例
工厂模式(创建型)规范创建对象
// 定义工厂函数
function createObject(type) {
let obj;
if (type === 'person') {
obj = new Person();
} else if (type === 'animal') {
obj = new Animal();
}
// 可以根据需求继续添加其他类型的对象
return obj;
}
// 定义Person类
class Person {
constructor() {
this.name = 'Human';
}
sayHello() {
console.log('Hello, I am a person!');
}
}
// 定义Animal类
class Animal {
constructor() {
this.name = 'Animal';
}
sayHello() {
console.log('Hello, I am an animal!');
}
}
// 使用工厂函数创建对象
const person = createObject('person');
person.sayHello(); // 输出: Hello, I am a person!
const animal = createObject('animal');
animal.sayHello(); // 输出: Hello, I am an animal!
未完待续...