标签:授权 一模一样 经理 作用 目录 fir 应用 gre 代理模式
面试敲门砖、进阶垫脚石、设计有模式、代码更合理
Javascript 设计模式系统讲解与应用 (练习代码)
npm init
npm i webpack webpack-cli --save-dev
//add webapck.dev.config.js file
module.exports = {
entry: './src/index.js',
output: {
path: __dirname,
filename: './release/bundle.js'
}
}
# package.json
"dev": "webpack --config ./webpack.dev.config.js --mode development"
npm i webpack-dev-server html-webpack-plugin -D
// webapck.dev.config.js
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
entry: './src/index.js',
output: {
path: __dirname,
filename: './release/bundle.js'
},
plugins: [
new HtmlWebpackPlugin({
template: './index.html'
})
],
devServer: {
contentBase: path.join(__dirname, './release'), // 设置根目录
open: true, // 自动打开浏览器
port: 9000
}
}
"dev": "webpack-dev-server --config ./webpack.dev.config.js --mode development"
支持babel npm i babel-core babel-loader babel-polyfill babel-preset-es2015 babel-preset-latest -D
新增babel配置文件 .babelrc
{
"presets": ["es2015", "latest"],
"plugins": []
}
再次修改webpack.config.js
// 新增module
module: {
rules: [{
test: /\.js?$/, // 我们要去检验哪些文件
exclude: /(node_modules)/, // 跳过哪些文件
loader: 'babel-loader' // 使用的loader
}]
},
设计准则:
小准则:
S O L I D 五大设计原则
function loadImg(src) {
var promise = new Promise(function(resolve, reject) {
var img = document.createElement('img')
img.onload = function () {
resolve(img)
}
img.onerror = function () {
reject('图片加载失败')
}
img.src = src
})
return promise
}
var src = 'https://www.imooc.com/static/img/index/logo.png'
var result = loadImg(src)
result.then(function (img) {
console.log('img.width', img.width)
return img
}).then(function (img) {
console.log('img.height', img.height)
}).catch(function (err) {
console.error(err)
})
就是3-3的代码
从设计到模式
体会什么是设计?设计是设计,模式是模式,两者是分离的。
该如何学习设计模式?
其实设计模式大致分为三种类型:
这23种设计模式分别分散在这三种类型中。
UML类图
class Car {
constructor(number, name) {
this.number = number
this.name = name
}
}
class Kuaiche extends Car {
constructor(number, name) {
super(number, name)
this.Price = 1
}
}
class Zhuanche extends Car {
constructor(number, name) {
super(number, name)
this.Price = 2
}
}
class Trip {
constructor(car) {
this.car = car
}
start() {
console.log(`行程开始,名称:${this.car.name},车牌号:${this.car.Price}`)
}
end() {
console.log(`行程结束,价格:${this.car.Price * 5}`)
}
}
let car = new Kuaiche('101', '捷达')
let trip = new Trip(car)
trip.start()
trip.end()
// 车
class Car {
constructor(num) {
this.num = num
}
}
// 入口摄像头
class Camera {
shot(car) {
return {
num: car.num,
inTime: Date.now()
}
}
}
// 出口显示器
class Screen {
show(car, inTime) {
console.log('车牌号', car.num)
console.log('停车时间', Date.now() - inTime)
}
}
// 停车场
class Park {
constructor(floors) {
this.floors = floors || []
this.camera = new Camera()
this.screen = new Screen()
this.carList = {}
}
in(car) {
// 获取摄像头的信息:号码 时间
const info = this.camera.shot(car)
// 停到某个车位
const i = parseInt(Math.random() * 100 % 100)
const place = this.floors[0].places[i]
place.in()
info.place = place
// 记录信息
this.carList[car.num] = info
}
out(car) {
// 获取信息
const info = this.carList[car.num]
const place = info.place
place.out()
// 显示时间
this.screen.show(car, info.inTime)
// 删除信息存储
delete this.carList[car.num]
}
emptyNum() {
return this.floors.map(floor => {
return `${floor.index} 层还有 ${floor.emptyPlaceNum()} 个车位`
}).join('\n')
}
}
// 层
class Floor {
constructor(index, places) {
this.index = index
this.places = places || []
}
emptyPlaceNum() {
let num = 0
this.places.forEach(p => {
if (p.empty) {
num = num + 1
}
})
return num
}
}
// 车位
class Place {
constructor() {
this.empty = true
}
in() {
this.empty = false
}
out() {
this.empty = true
}
}
// 测试代码------------------------------
// 初始化停车场
const floors = []
for (let i = 0; i < 3; i++) {
const places = []
for (let j = 0; j < 100; j++) {
places[j] = new Place()
}
floors[i] = new Floor(i + 1, places)
}
const park = new Park(floors)
// 初始化车辆
const car1 = new Car('A1')
const car2 = new Car('A2')
const car3 = new Car('A3')
console.log('第一辆车进入')
console.log(park.emptyNum())
park.in(car1)
console.log('第二辆车进入')
console.log(park.emptyNum())
park.in(car2)
console.log('第一辆车离开')
park.out(car1)
console.log('第二辆车离开')
park.out(car2)
console.log('第三辆车进入')
console.log(park.emptyNum())
park.in(car3)
console.log('第三辆车离开')
park.out(car3)
原理
new
操作单独封装new
时,就要考虑是否该使用工厂模式示例
/**
* 工厂模式示例,逻辑如图:
*
* -------------------------- ----------------|
* | Creator | | Product |
* |------------------------| |---------------|
* | | | + name:String |
* |------------------------| -> |---------------|
* | + create(name):Product | | + init() |
* -------------------------- | + fn1() |
* | + fn2() |
* ----------------|
*/
class Product {
constructor(name) {
this.name = name;
}
init() {
console.log("init", this.name);
}
fn1() {
console.log("fn1", this.name);
}
fn2() {
console.log("fn2", this.name);
}
}
class Creator {
create(name) {
return new Product(name);
}
}
// 测试
const creator = new Creator();
const p1 = creator.create("test1");
const p2 = creator.create("test2");
p1.init();
p2.init();
p1.fn1();
p2.fn1();
p1.fn2();
p2.fn2();
场景
jQuery - $('div')
React.createElement
vue异步组件
React.createElement使用工厂模式的好处:如果我们不用 createElement 封装 new VNode(tag,attrs, children)
,在对生成VNode示例时我们还是让用户去验证各个属性参数,显示不合理,而且用了工厂模式后用户根本不关系内部构造函数怎么变化。
Vue异步加载组件完成后创建组件的模式
使用工厂模式把工厂内部构造函数与用户隔离
/**
* 单例模式
*/
class SingleObject {
login() {
console.log("login...");
}
}
// 创建一个静态自执行的方法
SingleObject.getInstance = (function() {
let instance;
return function() {
if (!instance) {
instance = new SingleObject();
}
return instance;
}
})()
// 测试
let obj1 = SingleObject.getInstance();
obj1.login();
let obj2 = SingleObject.getInstance();
obj2.login();
console.log(obj1 === obj2);
class LoginForm() {
constructor() {
this.state = 'hide'
}
hide() {
if(this.state === 'hide'){
console.log('已经隐藏')
return
}
this.state == 'hide'
consoel.log('隐藏成功')
}
show() {
if(this.state === 'show'){
console.log('已經顯示')
return
}
this.state === 'show'
console.log('顯示成功')
}
}
LoginForm.instance = (function(){
let instance
return function(){
if(!instance){
instance = new LoginForm()
}
return instance
}
})()
let login1 = LoginForm.instance()
login1.hide()
let login2 = LoginForm.instance()
login2.hide()
jQuery
永远只有一个
/**
* 适配器模式
*/
class Adapter {
specificRequest() {
return "旧的接口内容"
}
}
class Target {
constructor() {
this.adapter = new Adapter();
}
request() {
let info = this.adapter.specificRequest();
return `${info} - 处理... - 新的接口内容`;
}
}
// 测试
let target = new Target();
const r = target.request();
console.log(r);
场景
设计原则验证
/**
* 装饰器模式
*/
class Circle {
draw() {
console.log("画一个圆");
}
}
class Decorator {
constructor(circle) {
this.circle = circle;
}
draw() {
this.circle.draw();
this.setRedBorder(this.circle);
}
setRedBorder(circle) {
console.log("设置红色边框");
}
}
// 测试
let c = new Circle();
c.draw();
let d = new Decorator(c);
d.draw();
/**
* 代理模式
*/
class ReadImg {
constructor(filename) {
this.filename = filename;
this.loadFromDisk();
}
loadFromDisk() {
console.log("从硬盘加载数据" + this.filename);
}
display() {
console.log("显示数据" + this.filename);
}
}
class ProxyImg {
constructor(filename) {
this.realImg = new ReadImg(filename);
}
display() {
this.realImg.display();
}
}
// test
let proxyImg = new ProxyImg("1.png");
proxyImg.display();
// =================================
/**
* 使用ES6语法的Proxy类演示 代理模式的示例,明星 - 经纪人
*/
let star = {
name: "张xx",
age : 25,
phone: "138123456789"
}
let agent = new Proxy(star, {
get: function(target, key) {
if (key === "phone") {
return "agent phone: 13555555555";
}
else if (key === "price") {
return 150000;
}
return target[key];
},
set: function(target, key, val) {
if (key === "customPrice") {
if (val < 10000) {
throw new Error("价格太低");
} else {
target[key] = val;
return true;
}
}
}
})
// test
console.log(agent.name);
console.log(agent.phone);
console.log(agent.age);
console.log(agent.price);
agent.customPrice = 120000; // OK
console.log(agent.customPrice);
agent.customPrice = 1000; // Error
console.log(agent.customPrice);
/**
* 观察者模式,使用nodejs的events模块的示例
*/
const EventEmitter = require("events").EventEmitter;
// =========EventEmitter的基础用法=============
const emitter1 = new EventEmitter();
// 监听some事件
emitter1.on("some", info => {
console.log("fn1", info);
})
// 监听some事件
emitter1.on("some", info => {
console.log("fn2", info);
})
// 触发some事件
emitter1.emit("some", "xxxx");
// =============================================
// 下面使用继承来实现EventEmitter
class Dog extends EventEmitter {
constructor(name) {
super();
this.name = name;
}
}
let dog = new Dog("dog");
dog.on("bark", function() {
console.log(this.name, " barked-1");
})
dog.on("bark", function() {
console.log(this.name, " barked-2");
})
setInterval(() => {
dog.emit("bark")
}, 1000);
/**
* 观察者模式
*/
// 主题,保存状态,状态变化之后触发所有观察者对象
class Subject {
constructor() {
this.state = 0;
this.observers = [];
}
getState() {
return this.state;
}
setState(state) {
this.state = state;
this.notifyAllObservers();
}
notifyAllObservers() {
this.observers.forEach(observer => {
observer.update();
})
}
attach(observer) {
this.observers.push(observer);
}
}
// 观察者
class Observer {
constructor(name, subject) {
this.name = name;
this.subject = subject;
this.subject.attach(this);
}
update() {
console.log(`${this.name} update! state is: ${this.subject.state}`);
}
}
// 测试
let s = new Subject();
let o1 = new Observer("o1", s);
let o2 = new Observer("o2", s);
let o3 = new Observer("o3", s);
let o4 = new Observer("o4", s);
s.setState(1);
s.setState(2);
/**
* 迭代器模式
*/
class Iterator {
constructor(container) {
this.list = container.list;
this.index = 0;
}
next() {
if (this.hasNext()) {
return this.list[this.index++];
}
return null;
}
hasNext() {
if (this.index >= this.list.length) {
return false;
}
return true;
}
}
class Container {
constructor(list) {
this.list = list;
}
// 生成遍历器
getIterator() {
return new Iterator(this);
}
}
// 测试
const arr = [1, 2, 3, 4, 5];
let container = new Container(arr);
let it = container.getIterator();
while(it.hasNext()) {
console.log(it.next());
}
// ============= 使用ES6的迭代器生成 =============
function each(data) {
// 生成遍历器
let it = data[Symbol.iterator]();
let item;
do {
// 遍历器生成可迭代内容,包含value和done属性,
// 其中done属性代替自定义的hasNext()方法,
// false表示还有数据,true则表示已经迭代完成
item = it.next();
if (!item.done) {
console.log(item.value);
}
} while (!item.done);
}
// ES6的Iterator已经封装在了语法 for...of 中,直接使用即可
function each2(data) {
for (const item of data) {
console.log(item);
}
}
// 测试
const arr2 = [10, 20, 30, 40, 50, 60];
let m = new Map();
m.set("a", 100);
m.set("b", 200);
m.set("c", 300);
each(arr2);
each(m);
each2(arr2);
each2(m);
/**
* 状态模式
*/
// 模拟红绿灯状态
class State {
constructor(color) {
this.color = color;
}
handle(context) {
console.log(`切换到 ${this.color} `);
context.setState(this);
}
}
// 主体
class Context {
constructor() {
this.state = null;
}
getState() {
return this.state;
}
setState(state) {
this.state = state;
}
}
// 测试
let context = new Context();
let green = new State("绿灯");
let yellow = new State("黄灯");
let red = new State("红灯");
// 绿灯亮
green.handle(context);
console.log(context.getState());
// 黄灯亮
yellow.handle(context);
console.log(context.getState());
// 红灯亮
red.handle(context);
console.log(context.getState());
import * as fs from "fs";
import * as StateMachine from 'javascript-state-machine';
import * as request from 'request';
// promise state: resolve(pending => fullfilled), reject(pending => rejected)
const fsm = new StateMachine({
init: 'pending',
transitions: [
{
name: 'resolve',
form: 'pending',
to: 'fullfilled'
}, {
name: 'reject',
from: 'pending',
to: 'rejected'
}
],
methods: {
onResolve: function(state, data, data1) {
// sate 当前状态机实例;data fsm.resolve(xxx) 传递的参数
// console.log(state, data)
data.succFnList.forEach(fn => fn(data1));
},
onReject: function(state, data) {
data.failFnList.forEach(fn => fn());
}
},
});
class MyPromise {
succFnList: any[];
failFnList: any[];
constructor(fn) {
this.succFnList = [];
this.failFnList = [];
fn((data) => {
// resolve 函数
fsm.resolve(this, data);
},
() => {
// reject 函数
fsm.reject(this);
});
}
then(succFn, failFn) {
this.succFnList.push(succFn);
this.failFnList.push(failFn);
}
}
function downloadImg(src) {
const promise = new MyPromise(function(resolve, reject) {
request(src, function(error, response, body) {
if (error) {
reject();
}
resolve(body);
})
});
return promise;
}
const imgSrc = 'https://www.npmjs.com/package/javascript-state-machine';
const imgPromise = downloadImg(imgSrc);
imgPromise.then(function(data) {
console.log(fsm.state)
fs.writeFileSync('./test.html', data)
}, function(error) {
console.log(error);
});
/**
* 原型模式
* prototype可以理解为ES6中class的一种底层原理,但是class是实现面向对象的基础,并不是服务于某个模式
*/
// 创建一个原型
let prototype = {
getName: function() {
return this.first + " " + this.last;
},
say: function() {
console.log("Hello!");
}
}
// 基于原型创建x
let x = Object.create(prototype);
x.first = "A";
x.last = "B";
console.log(x.getName());
x.say();
// 基于原型创建y
let y = Object.create(prototype);
y.first = "C";
y.last = "D";
console.log(y.getName());
y.say();
/**
* 桥接模式
*/
class Color {
constructor(name) {
this.name = name;
}
}
class Shape {
constructor(name, color) {
this.name = name;
this.color = color;
}
draw() {
console.log(`使用${this.color.name}颜色画了一个${this.name}`);
}
}
// 测试
let red = new Color("red");
let yellow = new Color("yellow");
let circle = new Shape("circle", red);
circle.draw();
let triangle = new Shape("triangle", yellow);
triangle.draw();
class TrainOrder {
create () {
console.log('创建火车票订单')
}
}
class HotelOrder {
create () {
console.log('创建酒店订单')
}
}
class TotalOrder {
constructor () {
this.orderList = []
}
addOrder (order) {
this.orderList.push(order)
return this
}
create () {
this.orderList.forEach(item => {
item.create()
})
return this
}
}
// 可以在购票网站买车票同时也订房间
let train = new TrainOrder()
let hotel = new HotelOrder()
let total = new TotalOrder()
total.addOrder(train).addOrder(hotel).create()
let examCarNum = 0 // 驾考车总数
/* 驾考车对象 */
class ExamCar {
constructor(carType) {
examCarNum++
this.carId = examCarNum
this.carType = carType ? '手动档' : '自动档'
this.usingState = false // 是否正在使用
}
/* 在本车上考试 */
examine(candidateId) {
return new Promise((resolve => {
this.usingState = true
console.log(`考生- ${ candidateId } 开始在${ this.carType }驾考车- ${ this.carId } 上考试`)
setTimeout(() => {
this.usingState = false
console.log(`%c考生- ${ candidateId } 在${ this.carType }驾考车- ${ this.carId } 上考试完毕`, 'color:#f40')
resolve() // 0~2秒后考试完毕
}, Math.random() * 2000)
}))
}
}
/* 手动档汽车对象池 */
ManualExamCarPool = {
_pool: [], // 驾考车对象池
_candidateQueue: [], // 考生队列
/* 注册考生 ID 列表 */
registCandidates(candidateList) {
candidateList.forEach(candidateId => this.registCandidate(candidateId))
},
/* 注册手动档考生 */
registCandidate(candidateId) {
const examCar = this.getManualExamCar() // 找一个未被占用的手动档驾考车
if (examCar) {
examCar.examine(candidateId) // 开始考试,考完了让队列中的下一个考生开始考试
.then(() => {
const nextCandidateId = this._candidateQueue.length && this._candidateQueue.shift()
nextCandidateId && this.registCandidate(nextCandidateId)
})
} else this._candidateQueue.push(candidateId)
},
/* 注册手动档车 */
initManualExamCar(manualExamCarNum) {
for (let i = 1; i <= manualExamCarNum; i++) {
this._pool.push(new ExamCar(true))
}
},
/* 获取状态为未被占用的手动档车 */
getManualExamCar() {
return this._pool.find(car => !car.usingState)
}
}
ManualExamCarPool.initManualExamCar(3) // 一共有3个驾考车
ManualExamCarPool.registCandidates([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) // 10个考生来考试
/**
* 策略模式
*/
// 普通情况下,没有使用策略模式
class User {
constructor(type) {
this.type = type;
}
buy() {
if (this.type === "ordinary") {
console.log("普通用户购买");
} else if (this.type === "member") {
console.log("会员用户购买");
} else if (this.type === "vip") {
console.log("高级会员购买");
}
}
}
// 使用
let u1 = new User("ordinary");
u1.buy();
let u2 = new User("member");
u2.buy();
let u3 = new User("vip");
u3.buy();
// ================ 使用策略模式进行调整 ===================
class OrdinaryUser {
buy() {
console.log("普通用户购买");
}
}
class MemberUser {
buy() {
console.log("会员用户购买");
}
}
class VipUser {
buy() {
console.log("高级会员用户购买");
}
}
// 测试
let ou = new OrdinaryUser();
ou.buy();
let mu = new MemberUser();
mu.buy();
let vu = new VipUser();
vu.buy();
/**
* 职责链模式
*/
class Action {
constructor(name) {
this.name = name;
this.nextAction = null;
}
setNextAction(action) {
this.nextAction = action;
}
handle() {
console.log(`${this.name} 执行了操作`);
if (this.nextAction) {
this.nextAction.handle();
}
}
}
// 测试
let a1 = new Action("组长");
let a2 = new Action("经理");
let a3 = new Action("总监");
a1.setNextAction(a2);
a2.setNextAction(a3);
a1.handle();
/**
* 命令模式
*/
class Receiver {
exec() {
console.log("执行");
}
}
class Command {
constructor(receiver) {
this.receiver = receiver;
}
cmd() {
console.log("触发命令");
this.receiver.exec();
}
}
class Invoker {
constructor(command) {
this.command = command;
}
invoke() {
console.log("开始");
this.command.cmd();
}
}
// 测试
let soldier = new Receiver();
let trumpeter = new Command(soldier);
let general = new Invoker(trumpeter);
general.invoke();
/**
* 备忘录模式
*/
// 备忘类
class Memento {
constructor(content) {
this.content = content;
}
getContent() {
return this.content;
}
}
// 备忘列表
class CareTaker {
constructor() {
this.list = [];
}
add(memento) {
this.list.push(memento);
}
get(index) {
return this.list[index];
}
}
// 编辑器
class Editor {
constructor() {
this.content = null;
}
setContent(content) {
this.content = content;
}
getContent() {
return this.content;
}
saveContentToMemento() {
return new Memento(this.content);
}
getContentFromMemento(memento) {
this.content = memento.getContent();
}
}
// 测试
let editor = new Editor();
let careTaker = new CareTaker();
editor.setContent("111");
editor.setContent("222");
careTaker.add(editor.saveContentToMemento()); // 备份
editor.setContent("333");
careTaker.add(editor.saveContentToMemento()); // 备份
editor.setContent("444");
console.log(editor.getContent());
editor.getContentFromMemento(careTaker.get(1)); // 撤销
console.log(editor.getContent());
editor.getContentFromMemento(careTaker.get(0)); // 撤销
console.log(editor.getContent());
/**
* 中介者模式
*/
class A {
constructor() {
this.number = 0;
}
setNumber(num, m) {
this.number = num;
if (m) {
m.setB();
}
}
}
class B {
constructor() {
this.number = 0;
}
setNumber(num, m) {
this.number = num;
if (m) {
m.setA();
}
}
}
class Mediator {
constructor(a, b) {
this.a = a;
this.b = b;
}
setA() {
let number = this.b.number;
this.a.setNumber(number / 100);
}
setB() {
let number = this.a.number;
this.b.setNumber(number * 100);
}
}
// 测试
let a = new A();
let b = new B();
let m = new Mediator(a, b);
a.setNumber(100, m);
console.log(a.number, b.number);
b.setNumber(100, m);
console.log(a.number, b.number);
class Context {
constructor() {
this._list = []; // 存放 终结符表达式
this._sum = 0; // 存放 非终结符表达式(运算结果)
}
get sum() {
return this._sum;
}
set sum(newValue) {
this._sum = newValue;
}
add(expression) {
this._list.push(expression);
}
get list() {
return [...this._list];
}
}
class PlusExpression {
interpret(context) {
if (!(context instanceof Context)) {
throw new Error("TypeError");
}
context.sum = ++context.sum;
}
}
class MinusExpression {
interpret(context) {
if (!(context instanceof Context)) {
throw new Error("TypeError");
}
context.sum = --context.sum;
}
}
/** 以下是测试代码 **/
const context = new Context();
// 依次添加: 加法 | 加法 | 减法 表达式
context.add(new PlusExpression());
context.add(new PlusExpression());
context.add(new MinusExpression());
// 依次执行: 加法 | 加法 | 减法 表达式
context.list.forEach(expression => expression.interpret(context));
console.log(context.sum);
标签:授权 一模一样 经理 作用 目录 fir 应用 gre 代理模式
原文地址:https://www.cnblogs.com/xulonglong/p/js-she-ji-mo-shi-dai-zheng-li.html