设计模式之工厂模式
工厂模式
简单工厂模式
- 批量生产对象的时候没有必要一个一个对象去创建,减少重复性代码。
- 在函数内部创建一个空对象
- 再给这个对象添加属性和方法
- 将包装好的对象返回处理啊
function createPerson(name) {
const o = {};
o.name = name;
o.getName = function() {
console.log(this.name);
}
return o;
}
const person1 = createPerson('lazy');
person1.getName(); // lazy
console.log(person1.name); // lazy
工厂方法
function Person(name) {
this.name = name;
}
Person.prototype.getName = function() {
console.log(this.name)
}
function Car(model) {
this.model = model;
}
Car.prototype.getModel = function() {
console.log(this.model)
}
function create(type, param) {
if(this instanceof create) { // 判断后面的构造函数的原型,是不是前面对象的原型链里
return new this[type](param);
}else {
return new create(type, param);
}
}
create.prototype = {
person: Person,
car: Car
}
const person1 = new create('person', '张三');
person1.getName(); // 张三
const car1 = create('car', 'Benz');
car1.getModel(); // Benz
-
new create('person', '张三') 发生了什么?
- 将 person1 的 proro(原型链) 指向了 create 的 prototype(原型)
-
new thistype 发生了什么?
- new thistype = new Person('张三')
- 将 create 的 proro(原型链) 指向了 Person 的 prototype(原型)
ES6 class 写法
class Person {
constructor(name) {
this.name = name;
}
getName() {
console.log(this.name);
}
}
class Car {
constructor(model) {
this.model = model;
}
getModel() {
console.log(this.model);
}
}
class Create {
static createFather = {
person: Person,
car: Car
}
constructor(type, param) {
return new Create.createFather[type](param);
}
static create = function(...args) {
return new this(...args)
}
}
// Create.prototype.person = Person;
// Create.prototype.car = Car;
const person1 = new Create('person', '张三');
person1.getName(); // 张三
const car1 = Create.create('car', 'Benz');
car1.getModel(); // Benz
本文来自博客园,作者:懒惰ing,转载请注明原文链接:https://www.cnblogs.com/landuo629/p/14318455.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?