Skip to content

Commit 2f66747

Browse files
committed
抽象工厂模式
1 parent a95a179 commit 2f66747

File tree

2 files changed

+51
-2
lines changed

2 files changed

+51
-2
lines changed
Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,46 @@
1-
// 抽象工厂模式(Abstract Factory Pattern)
1+
// 抽象工厂模式(Abstract Factory Pattern)
2+
3+
class User {
4+
constructor (type) {
5+
if (new.target === User) {
6+
throw new Error('抽象类不能实例化!')
7+
}
8+
this.type = type
9+
}
10+
}
11+
12+
class UserOfWechat extends User {
13+
constructor (name) {
14+
super('wechat')
15+
this.name = name
16+
this.viewPage = ['首页', '通讯录', '发现页']
17+
}
18+
}
19+
20+
class UserOfQQ extends User {
21+
constructor (name) {
22+
super('qq')
23+
this.name = name
24+
this.viewPage = ['首页', '通讯录', '发现页']
25+
}
26+
}
27+
28+
function getUser (type) {
29+
switch (type) {
30+
case 'wechat':
31+
return UserOfWechat
32+
break
33+
case 'qq':
34+
return UserOfQQ
35+
break
36+
default:
37+
throw new Error('参数错误')
38+
break
39+
}
40+
}
41+
42+
let WechatUserClass = getUser('wechat')
43+
let QQUserClass = getUser('qq')
44+
45+
let wechatUser = new WechatUserClass('卡卡罗特')
46+
let qqUser = new QQUserClass('贝吉塔')

README.md

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,11 @@
2727
场景:一些基本部件不会变,而其组合经常变化的时候。
2828

2929
> [抽象工厂模式(Abstract Factory Pattern)](/Example/Abstract-Factory-Pattern.js)
30-
30+
31+
定义:抽象工厂模式提供了一种方式,可以将一组具有同一主题的单独的工厂封装起来。或者说,是其他工厂的工厂。
32+
目的:提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。
33+
场景:系统的产品有多于一个的产品族,而系统只消费其中某一族的产品。
34+
3135
> [原型模式(Prototype Pattern)](/Example/Prototype-Pattern.js)
3236
3337
***

0 commit comments

Comments
 (0)