描述:保证一个类仅有实例,并提供一个可以全局访问他的点,它通常用于管理应用程序的全局状态或资源,例如一个唯一的状态管理器。
代码示例:
class Singleton {
constructor() {
if (!Singleton.instance) {
Singleton.instance = this;
}
return Singleton.instance;
}
}
const instance1 = new Singleton();
const instance2 = new Singleton();
console.log(instance1 === instance2); // true
描述:观察者模式用于建立对象之间的一对多依赖关系,使得当一个对象的状态发生变化时,所有依赖它的对象都会得到通知。在前端中,常见于事件处理和数据变化监听。
代码示例
class Observable {
constructor() {
this.observers = [];
}
addObserver(observer) {
this.observers.push(observer);
}
notifyObservers(data) {
this.observers.forEach(observer => observer.update(data));
}
}
class Observer {
update(data) {
console.log(`Received data: ${data}`);
}
}
const subject = new Observable();
const observer1 = new Observer();
const observer2 = new Observer();
subject.addObserver(observer1);
subject.addObserver(observer2);
subject.notifyObservers("Hello, observers!");
描述:工厂模式用于通过一个共同的接口来创建对象,隐藏了对象的创建细节。在前端中,可以用于创建不同类型的UI组件。
代码示例
class Button {
render() {
console.log("Rendering a button");
}
}
class Input {
render() {
console.log("Rendering an input");
}
}
class UIFactory {
create(type) {
switch (type) {
case "button":
return new Button();
case "input":
return new Input();
default:
throw new Error("Invalid type");
}
}
}
const factory = new UIFactory();
const button = factory.create("button");
const input = factory.create("input");
button.render(); // Logs: "Rendering a button"
input.render(); // Logs: "Rendering an input"
描述:装饰者模式用于动态地将责任添加到对象上,以扩展对象的功能。在前端中,可以用于增强组件的功能。
代码示例:
class Component {
operation() {
console.log("Basic operation");
}
}
class Decorator {
constructor(component) {
this.component = component;
}
operation() {
console.log("Decorator operation");
this.component.operation();
}
}
const component = new Component();
const decoratedComponent = new Decorator(component);
component.operation(); // Logs: "Basic operation"
decoratedComponent.operation(); // Logs: "Decorator operation" followed by "Basic operation"
描述:策略模式定义了一系列算法,并将每个算法封装起来,使得它们可以互相替换。在前端中,可以用于处理不同的数据转换、验证或处理逻辑。
代码示例
class PaymentStrategy {
constructor(paymentMethod) {
this.paymentMethod = paymentMethod;
}
pay(amount) {
return this.paymentMethod.pay(amount);
}
}
class CreditCardPayment {
pay(amount) {
console.log(`Paying ${amount} using credit card.`);
}
}
class PayPalPayment {
pay(amount) {
console.log(`Paying ${amount} using PayPal.`);
}
}
const creditCardPayment = new PaymentStrategy(new CreditCardPayment());
creditCardPayment.pay(100); // Logs: "Paying 100 using credit card."
const payPalPayment = new PaymentStrategy(new PayPalPayment());
payPalPayment.pay(50); // Logs: "Paying 50 using PayPal."
描述:适配器模式用于将一个类的接口转换成客户端期望的另一个接口。在前端中,可以用于处理不同数据格式或API之间的适配。
代码示例
class OldApi {
request() {
return "Response from old API";
}
}
class NewApi {
fetch() {
return "Response from new API";
}
}
class Adapter {
constructor(api) {
this.api = api;
}
request() {
if (this.api instanceof OldApi) {
return this.api.request();
} else if (this.api instanceof NewApi) {
return this.api.fetch();
}
}
}
const oldApi = new OldApi();
const newApi = new NewApi();
const oldAdapter = new Adapter(oldApi);
console.log(oldAdapter.request()); // Logs: "Response from old API"
const newAdapter = new Adapter(newApi);
console.log(newAdapter.request()); // Logs: "Response from new API"
描述:命令模式将请求或操作封装成对象,允许参数化调用。在前端中,可以用于处理用户操作、撤销/重做功能等。
代码描述:
class Command {
constructor(receiver) {
this.receiver = receiver;
}
execute() {
this.receiver.performAction();
}
}
class Receiver {
performAction() {
console.log("Action performed");
}
}
const receiver = new Receiver();
const command = new Command(receiver);
command.execute(); // Logs: "Action performed"
描述: 代理模式控制对其他对象的访问,可以添加额外的逻辑,如缓存、权限控制等。在前端中,可以用于懒加载、请求缓存等场景。
代码描述
class RealImage {
constructor(filename) {
this.filename = filename;
this.loadImageFromDisk();
}
display() {
console.log(`Displaying image: ${this.filename}`);
}
loadImageFromDisk() {
console.log(`Loading image: ${this.filename}`);
}
}
class ProxyImage {
constructor(filename) {
this.filename = filename;
this.realImage = null;
}
display() {
if (!this.realImage) {
this.realImage = new RealImage(this.filename);
}
this.realImage.display();
}
}
const image1 = new ProxyImage("image1.jpg");
image1.display(); // Logs: "Loading image: image1.jpg" followed by "Displaying image: image1.jpg"
image1.display(); // Logs: "Displaying image: image1.jpg" (no additional loading)
const image2 = new ProxyImage("image2.jpg");
image2.display(); // Logs: "Loading image: image2.jpg" followed by "Displaying image: image2.jpg"
描述:迭代器模式提供一种顺序访问聚合对象元素的方法,而无需暴露其内部表示。在前端中,可以用于遍历数据集合。
代码描述:
class Iterator {
constructor(collection) {
this.collection = collection;
this.index = 0;
}
hasNext() {
return this.index < this.collection.length;
}
next() {
return this.collection[this.index++];
}
}
const collection = [1, 2, 3, 4, 5];
const iterator = new Iterator(collection);
while (iterator.hasNext()) {
console.log(iterator.next());
}
描述:状态模式允许对象在内部状态变化时改变其行为。在前端中,可以用于管理复杂的UI状态转换。
代码描述
class State {
handle() {
console.log("Default state handling");
}
}
class ConcreteStateA extends State {
handle() {
console.log("State A handling");
}
}
class ConcreteStateB extends State {
handle() {
console.log("State B handling");
}
}
class Context {
constructor() {
this.state = new State();
}
setState(state) {
this.state = state;
}
request() {
this.state.handle();
}
}
const context = new Context();
context.request(); // Logs: "Default state handling"
context.setState(new ConcreteStateA());
context.request(); // Logs: "State A handling"
context.setState(new ConcreteStateB());
context.request(); // Logs: "State B handling"