web前端全系列 教程
1839个小节阅读:2243.8k
目录
鸿蒙应用开发
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
策略模式的本意将算法的使⽤与算法的实现分离开来,避免多重判断调⽤哪些算法。适⽤于有多个判断分⽀的场景
xxxxxxxxxx
461// 对于vip客户
2function vipPrice() {
3 this.discount = 0.5;
4}
5vipPrice.prototype.getPrice = function (price) {
6 return price * this.discount;
7}
8// 对于超级客户
9function superVipPrice() {
10 this.discount = 0.3;
11}
12superVipPrice.prototype.getPrice = function (price) {
13 return price * this.discount;
14}
15// 对于普通客户
16function Price() {
17 this.discount = 1;
18}
19Price.prototype.getPrice = function (price) {
20 return price;
21}
22// 上下⽂,对于客户端的使⽤
23function Context() {
24 this.name = '';
25 this.strategy = null;
26 this.price = 0;
27}
28Context.prototype.set = function (name, strategy, price) {
29 this.name = name;
30 this.strategy = strategy;
31 this.price = price;
32}
33Context.prototype.getResult = function () {
34 console.log(this.name + ' 的结账价为: ' +
35this.strategy.getPrice(this.price));
36 }
37var context = new Context();
38var vip = new vipPrice();
39context.set('vip客户', vip, 200);
40context.getResult();
41var old = new superVipPrice();
42context.set('超级Vip客户', old, 200);
43context.getResult();
44var Price = new Price();
45context.set('普通客户', Price, 200);
46context.getResult();