跳到主要内容

工厂模式

介绍


工厂模式 提供了一种创建对象的方法,对使用方隐藏了对象的具体实现细节,并使用一个公共的接口来创建对象

特点


优点

  • 工厂类含有必要的判断逻辑, 实现了对责任的分割,它提供了专门的工厂类用于创建对象
  • 用户只需要关心所需产品对应的工厂,无须关心创建细节
  • 在系统中加入新产品时,无须修改抽象工厂和抽象产品提供的接口,符合“开闭原则”

缺点

  • 添加新产品时,需要编写新的具体产品类,一定程度上增加了系统的复杂度
  • 考虑到系统的可扩展性,需要引入抽象层,在客户端代码中均使用抽象层进行定义,增加了系统的抽象性和理解难度

实现


完整代码

class Person {
constructor(name,grade){
this.name = name;
this.grade = grade;
}
say(){
console.log(this.name+'正在说');
}
do(){
console.log(this.name+'正在做');
}
}
class Animal{
constructor(name,color){
this.name = name;
this.color = color;
}
eat(){
console.log(this.name+'在吃');
}
run(){
console.log(this.name+'在跑');
}
}
class Creator{
createPerson(name,grade){
return new Person(name,grade);
}
createAnimal(name,color){
return new Animal(name,color);
}
}

测试用例

const creator = new Creator();
const person1 = creator.createPerson('李白','诗仙');
person1.say();
person1.do();
const person2 = creator.createPerson('杜甫','诗圣');
person2.say();
person2.do();
const person3 = creator.createPerson('白居易','诗诗');
person3.say();
person3.do();
const animal1 = creator.createAnimal('小花','白色');
animal1.eat();
animal1.run();
const animal2 = creator.createAnimal('小兰','蓝色');
animal2.eat();
animal2.run();

场景


前端本地存储的封装

:::details 点击查看代码

function StorageFactory(){
const storageMap=new Map();
return (key,storage=localStorage)=>{
if(storageMap.has(key)){
return storageMap.get(key);
}
const model={
key,
set(value){
storage.setItem(this.key,JSON.stringify(value));
},
get(){
const result=storage.getItem(this.key);
return result&&JSON.parse(result)
},
remove(){
storage.removeItem(this.key);
}
}
storageMap.set(key,model);
return model;
}
}
const goodId=StorageFactory()('goodId',localStorage);
goodId.set('张文强');
console.log(goodId.get());
const order=StorageFactory()('order',sessionStorage);
order.set({goodId:'张文强',price:'无价'});
console.log(order.get());

:::