观察者模式、发布/订阅模式、迭代器模式、职责链模式、委托模式、策略模式、中介者模式、模版方法模式、命令模式、备忘录模式、状态模式、访问者模式、解释器模式
let observer_ids=0;
let observed_ids=0;
//观察者类
class Observer {
constructor() {
this.id = observer_ids++;
}
//观测到变化后的处理
update(ob){
console.log("观察者" + this.id + `-检测到被观察者${ob.id}变化`);
}
}
//被观察者列
class Observed {
constructor() {
this.observers = [];
this.id=observed_ids++;
}
//添加观察者
addObserver(observer) {
this.observers.push(observer);
}
//删除观察者
removeObserver(observer) {
this.observers = this.observers.filter(o => {
return o.id != observer.id;
});
}
//通知所有的观察者
notify(ob) {
this.observers.forEach(observer => {
observer.update(ob);
});
}
}
let mObserved=new Observed();
let mObserver1=new Observer();
let mObserver2=new Observer();
mObserved.addObserver(mObserver1);
mObserved.addObserver(mObserver2);
mObserved.notify();
class eventBus {
constructor() {
this.events = new Map()
}
subscribe(eventname,fn) {
let fns = this.events.get(eventname)
if(!fns){
fns = []
fns.push(fn)
this.events.set(eventname,fns)
}else {
fns.push(fn)
}
}
publish(...args) {
let eventname = args.shift()
let fns = this.events.get(eventname)
for(let i = -1; fns[++i];){
fns[i](args)
}
}
}
var eventBus1 = new eventBus()
eventBus1.subscribe(3000,function(data) {
console.log(data)
})
eventBus1.publish(3000,'发布了一个3000的房子')
class Iterator {
constructor(container) {
this.list = container.list
this.index = 0
}
next() {
if(this.hasNext()) {
return this.list[this.index++]
}
}
hasNext() {
if(this.index >= this.list.length) {
return false
}
return true
}
}
class Container {
constructor(list) {
this.list = list
}
// 生成遍历器
getIterator() {
return new Iterator(this)
}
}
let container = new Container([1,2,3,4,5,6])
let iterator = container.getIterator()
while(iterator.hasNext()) {
console.log(iterator.next());
}
var obj = {
a:function(){
console.log('aaa')
return this
}
b:function(){
console.log('bbb')
return this
}
}
console.log(a.b().c())
<ul>
<li>aaaaaaaaaaaaa<li>
ul>
window.onload = function(){
var oUl = document.querySelector('ul')
oUl.onclick=function(e){
var e = e || window.event
target = e.target || e.srcElement
if(target.nodeName.toLowerCase() === 'li'){
console.log(target.innerHTML)
}
}
var oLi = document.createElement('li')y
oLi.innerHtml = 'eeee'
oul.appendchild(oLi)
}
let calculateBonus = function (level,salary) {
if(level === 'S')
{
return salary*4;
}
if(level === 'A')
{
return salary*3;
}
if(level === 'B')
{
return salary*2;
}
}
calculateBonus('S',10000) //输出40000
calculateBonus('B',10000) //输出20000
let strategies = {
"S" :function(salary) {
return salary*4
},
"A" :function(salary) {
return salary*3
},
"B" :function(salary) {
return salary*2
},
"C" :function(salary) {
return salary*1
},
}
// 引用
let calculateBonus = function (level,salary) {
return strategies[level](salary);
}
calculateBonus('S',20000)//输出80000
class Olympiad {
constructor () {
this.players = []
}
join (player) {
this.players.push(player)
}
exit (player) {
this.players.splice(this.players.findIndex(item=>item.name === player.name), 1)
}
getResult () {
console.log('参赛所有方', this.players)
this.players.forEach(item => {
console.log(item.name, item.state)
})
}
}
class player {
constructor (name) {
this.name = name
this.state = 'ready'
}
lose () {
this.state = 'lose'
}
win () {
this.state = 'win'
}
}
const rabbit = new player('兔子')
const bear = new player('北极熊')
const chicken = new player('高卢鸡')
const eagle = new player('白头鹰')
const johnBull = new player('约翰牛')
const olympiad = new Olympiad ()
olympiad.join(rabbit)
olympiad.join(bear)
olympiad.join(chicken)
olympiad.join(eagle)
olympiad.join(johnBull)
olympiad.exit(chicken)
rabbit.win()
bear.win()
eagle.lose()
johnBull.lose()
olympiad.getResult()
var Beverage = function(){};
Beverage.prototype.boilWater = function(){
console.log( '把水煮沸' );
};
Beverage.prototype.brew = function(){
throw new Error( '子类必须重写brew方法' );
};
Beverage.prototype.pourInCup = function(){
throw new Error( '子类必须重写pourInCup方法' );
};
Beverage.prototype.addCondiments = function(){
throw new Error( '子类必须重写addCondiments方法' );
};
Beverage.prototype.customerWantsCondiments = function(){
return true; // 默认需要调料
};
Beverage.prototype.init = function(){
this.boilWater();
this.brew();
this.pourInCup();
if ( this.customerWantsCondiments() ){ // 如果挂钩返回true,则需要调料
this.addCondiments();
}
};
var CoffeeWithHook = function(){};
CoffeeWithHook.prototype = new Beverage();
CoffeeWithHook.prototype.brew = function(){
console.log( '用沸水冲泡咖啡' );
};
CoffeeWithHook.prototype.pourInCup = function(){
console.log( '把咖啡倒进杯子' );
};
CoffeeWithHook.prototype.addCondiments = function(){
console.log( '加糖和牛奶' );
};
CoffeeWithHook.prototype.customerWantsCondiments = function(){
return window.confirm( '请问需要调料吗?' );
};
var coffeeWithHook = new CoffeeWithHook();
coffeeWithHook.init();
class Receiver { // 接收者类
execute() {
console.log('接收者执行请求');
}
}
class Command { // 命令对象类
constructor(receiver) {
this.receiver = receiver;
}
execute () { // 调用接收者对应接口执行
console.log('命令对象->接收者->对应接口执行');
this.receiver.execute();
}
}
class Invoker { // 发布者类
constructor(command) {
this.command = command;
}
invoke() { // 发布请求,调用命令对象
console.log('发布者发布请求');
this.command.execute();
}
}
const warehouse = new Receiver(); // 仓库
const order = new Command(warehouse); // 订单
const client = new Invoker(order); // 客户
client.invoke();
/*
输出:
发布者发布请求
命令对象->接收者->对应接口执行
接收者执行请求
*/
class Memento {
constructor(content) {
this.content = content;
}
getContent() {
return this.content;
}
}
// 备忘列表
class CarTaker {
constructor() {
this.list = [];
}
add(memento) {
this.list.push(memento);
}
get(index) {
return this.list[index];
}
getList() {
return this.list
}
}
// 编辑器
class Editor {
constructor() {
this.content = null;
}
setContent(content) {
this.content = content;
}
getContent() {
return this.content;
}
saveContentToMemento() {
return new Memento(this.content);
}
getConentFromMemento(memento) {
this.content = memento.getContent();
}
}
// 测试代码
let editor = new Editor()
let careTaker = new CarTaker()
editor.setContent('111')
editor.setContent('222')
careTaker.add(editor.saveContentToMemento()) // 将当前222内容备份
editor.setContent('333')
careTaker.add(editor.saveContentToMemento()) // 将当前333内容备份
editor.setContent('444')
console.log(editor.getContent())
editor.getConentFromMemento(careTaker.get(1)) // 撤销
console.log(editor.getContent())
editor.getConentFromMemento(careTaker.get(0)) // 撤销
console.log(editor.getContent())
let HighState = {
show() {
console.log('绿色');
},
}
let MiddleState = {
show() {
console.log('黄色');
}
}
let LowState = {
show() {
console.log('红色');
}
}
let Battery = {
amount: 'heigh',
state: HighState,
// Bettery对象暴露的接口,用于设置对象的状态,并调用状态对象的接口,刷新对应状态的行为
show() {
this.setState();
// 把显示的逻辑委托给状态对象
this.state.show();
},
// 设置Bettery对象的状态,
setState() {
let amount = {
'heigh': () => {
this.state = HighState;
},
'middle': () => {
this.state = MiddleState;
},
'low': () => {
this.state = LowState;
}
}
amount[this.amount]();
}
}
Battery.show();
Battery.amount = 'middle';
Battery.show();
Battery.amount = 'low';
Battery.show();
var Visitor = (function () {
return {
splice: function () {
var args = Array.prototype.splice.call(arguments, 1);
return Array.prototype.splice.apply(arguments[0], args);
},
push : function () {
var len = arguments[0].length || 0;
var args = this.splice(arguments, 1);
arguments[0].length = len + arguments.length - 1;
return Array.prototype.push.apply(arguments[0], args);
},
pop: function () {
return Array.prototype.pop.apply(arguments[0]);
}
}
})();
var a = {};
Visitor.push(a, 1, 3, 4);
Visitor.push(a, 3, 4, 5);
Visitor.pop(a);
Visitor.splice(a, 1);
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);