需要定义对象变量的时候使用,避免反复的定义
let animal1 = {
name: '猫猫',
age: 4
}
let animal2 = {
name: '狗狗',
age: 5
}
// 以上太麻烦
class Animal {
constructor(name, age) {
this.name = name
this.age = age
}
}
let animal3 = new Animal('鼠鼠', 3)
console.log(animal1, animal2, animal3)
const user = {
powers: [],
setPowers (power) {
this.powers.push(power);
},
clone () {
var newForm = Object.create(this);
newForm.powers = Object.create(this.powers);
return newForm;
}
};
const temp1 = Object.create(user);
const temp2 = temp1.clone();
const temp3 = {
powers: [],
setPowers (power) {
this.powers.push(power);
},
clone () {
var newForm = Object.create(this);
newForm.powers = Object.create(this.powers);
return newForm;
}
};
class User {
constructor(role, power) {
this.role = role
this.power = power
}
}
let user1 = new User('admin', ['home', 'mine', 'about', 'manage'])
let user2 = new User('member', ['home', 'mine', 'about'])
let user3 = new User('assistant', ['home', 'finance', 'inventory'])
// 以上太麻烦
class Userc {
constructor(role, power) {
this.role = role
this.power = power
}
static GenerateUser (role, power) {
switch (role) {
case 'admin':
return new Userc('admin', ['home', 'mine', 'about', 'manage'])
break;
case 'member':
return new Userc('member', ['home', 'mine', 'about'])
break;
case 'assistant':
return new Userc('assistant', ['home', 'finance', 'inventory'])
break;
default:
return new Userc(role, power)
break
}
}
}
let user4 = Userc.GenerateUser('admin')
let user5 = Userc.GenerateUser('member')
let user6 = Userc.GenerateUser('assistant')
console.log(user1, user3)
// 抽象类
class User {
constructor(role, power) {
this.role = role
this.power = power
}
pushData () {
console.log('推送数据')
}
static GenerateUser (role, power) {
switch (role) {
case 'admin':
return new Admin()
break;
case 'member':
return new Member()
break;
case 'assistant':
return new Assistant()
break;
default:
return new User(role, power)
break
}
}
}
class Admin extends User {
constructor(role, power) {
super('admin', ['home', 'mine', 'about', 'manage'])
}
banUser () {
console.log('封禁用户')
}
}
class Member extends User {
constructor(role, power) {
super('member', ['home', 'mine', 'about'])
}
}
class Assistant extends User {
constructor(role, power) {
super('assistant', ['home', 'finance', 'inventory'])
}
handle () {
console.log('辅助处理数据')
}
}
let user1 = User.GenerateUser('admin')
let user2 = User.GenerateUser('member')
let user3 = User.GenerateUser('assistant')
console.log(user1, user3)
class Yagu {
constructor() {
this.name = "亚古兽"
this.level = 1
}
first () {
this.name = '暴龙兽'
this.level++
console.log('进化了', this.name, this.level)
}
second () {
this.name = '机械暴龙兽'
this.level++
console.log('进化了', this.name, this.level)
}
third () {
this.name = '战斗暴龙兽'
this.level++
console.log('进化了', this.name, this.level)
}
}
class Jiabu {
constructor() {
this.name = "加布兽"
this.level = 1
}
first () {
this.name = '加鲁鲁兽'
this.level++
console.log('进化了', this.name, this.level)
}
second () {
this.name = '兽人加鲁鲁'
this.level++
console.log('进化了', this.name, this.level)
}
third () {
this.name = '机械加鲁鲁'
this.level++
console.log('进化了', this.name, this.level)
}
}
class Evolution {
start (digitalMonster) {
digitalMonster.first()
digitalMonster.second()
digitalMonster.third()
}
}
const ev = new Evolution()
ev.start(new Yagu())
ev.start(new Jiabu())
class Singleton {
constructor(name) {
if (Singleton.instance) {
return Singleton.instance
}
else {
this.name = name
Singleton.instance = this
return Singleton.instance
}
}
}
console.log(new Singleton('张三'), new Singleton('李四'), new Singleton('张三') === new Singleton('李四'))
class User {
role = "admin"
power = ['home', 'mine', 'about', 'manage']
constructor(userName) {
this.userName = userName
}
login () {
console.log('login')
return this.power
}
}
// 不修改原有的类,在实例方法login前后各增加一个函数,并形成行的函数
User.decoration = function (instance) {
instance.before = function () {
console.log('before')
}
instance.after = function () {
console.log('after')
}
instance.loginC = function () {
this.before()
let result = this.login()
this.after()
return result
}
}
let user = new User()
User.decoration(user)
console.log(user.loginC())
class WxPlay {
constructor() {
}
pay () {
console.log('调用微信支付')
}
}
class AliPlay {
constructor() {
}
alipayPay () {
console.log('调用支付宝支付')
}
}
// 现有两个支付类,需要通过判断调用,但是由于支付方法不同,调用统一方法,所以进行二次封装,使方法名统一
class AliPlayHandle extends AliPlay {
constructor() {
super()
}
pay () {
this.alipayPay()
}
}
class Pay {
constructor(wx, ali) {
this.wx = wx
this.ali = ali
}
pay (way) {
this[way].pay()
}
}
const wx = new WxPlay()
const ali = new AliPlayHandle()
const pay = new Pay(wx, ali)
pay.pay('wx')
pay.pay('ali')
class PiggyBank {
constructor() {
this.money = 0
}
deposit(money) {
this.money += money
}
withdraw() {
return this.money
}
clear() {
this.money = 0
}
}
class Agent {
constructor() {
this.piggyBank = new PiggyBank()
}
set(num) {
this.piggyBank.deposit(num)
}
get() {
let temp = this.piggyBank.withdraw()
this.piggyBank.clear()
return temp
}
}
const agent = new Agent()
agent.set(10)
agent.set(10)
agent.set(10)
console.log(agent.get(), agent)
// 抽象类
class User {
constructor(instance) {
this.instance = instance
}
login () {
this.instance.login()
}
getPower () {
this.instance.getPower()
}
}
// 实现类
class Admin {
login () {
console.log('管理员登录')
}
getPower () {
console.log('管理员获取权限')
}
}
// 实现类
class Member {
login () {
console.log('用户登录')
}
getPower () {
console.log('用户获取权限')
}
}
const admin = new User(new Admin())
const member = new User(new Member())
admin.login()
admin.getPower()
member.login()
member.getPower()
// 规范支和叶的行为
class Element {
constructor(name) {
this.name = name
this.list = []
}
insert () {
throw new Error('没有重写insert方法')
}
output () {
throw new Error('没有重写output方法')
}
getNamePosition () {
throw new Error('没有重写getNamePosition方法')
}
}
// 定义树枝
class Branch extends Element {
constructor(name) {
super(name)
}
insert (ele) {
this.list.push(ele)
return this
}
output () {
console.log(this.name)
this.list.forEach(item => {
item.output()
});
}
getNamePosition (name, index = undefined) {
for (let i = 0; i < this.list.length; i++) {
const ele = this.list[i];
const temp = ele.getNamePosition(name, `${index ? index + '-' : ''}${i}`)
if (temp) return temp
}
if (name === this.name) return index
return false
}
}
// 定义树
class Leaf extends Element {
constructor(name) {
super(name)
}
output () {
console.log(this.name)
}
getNamePosition (name, index = 0) {
if (name === this.name) return index
return false
}
}
const root = new Branch('根')
const branch1 = new Branch('一级枝干1')
const branch2 = new Branch('一级枝干2')
const branch11 = new Branch('二级枝干11')
const branch12 = new Branch('二级枝干12')
const leaf1 = new Leaf('树叶1')
const leaf2 = new Leaf('树叶2')
const leaf3 = new Leaf('树叶3')
root.insert(branch1).insert(branch2)
branch1.insert(branch11).insert(branch12)
branch11.insert(leaf1)
branch12.insert(leaf2)
branch2.insert(leaf3)
root.output()
console.log(root.getNamePosition('树叶2'))
console.log(root.getNamePosition('树叶3'))
console.log(root)
leaf3.insert()
class Mouth {
constructor() {
this.observes = []
}
addObserve(observe) {
this.observes.push(observe)
return this
}
eat() {
console.log('吃吃吃')
this.observes.forEach(item => {
item.func()
})
}
}
class Organ {
constructor(name, func) {
this.name = name
this.func = func
}
}
const mouth = new Mouth()
const organ1 = new Organ('胃', () => console.log('分泌胃酸'))
const organ2 = new Organ('胆', () => console.log('分泌胆汁'))
const organ3 = new Organ('胰腺', () => console.log('分泌胰岛素'))
mouth.addObserve(organ1).addObserve(organ2).addObserve(organ3)
mouth.eat()
class PubSub {
constructor() {
this.message = {}
}
publisg(key, callback) {
this.message[key].push(callback)
return this
}
remove(key, callback) {
const element = this.message[key]
for (let i = 0; i < element; i++) {
if (callback === element[i]) {
this.message[key].splice(i, 1)
break
}
}
}
subscribe(key, data) {
this.message[key].forEach(item => {
item()
})
}
}
const a = (function () {
var b = 0
return {
add() {
return ++b
},
reduce() {
return --b
}
}
})()
console.log(a)
// 抽象命令类
class Command {
execute() {
throw new Error('该方法必须重写')
}
}
// 接收者类
class Receiver {
action() {
console.log('执行请求')
}
}
// 具体命令类
class ConcreteCommand extends Command {
constructor(receiver) {
super()
this.receiver = receiver
}
execute() {
this.receiver.action()
}
}
// 发送者类
class Invoker {
constructor(command) {
this.command = command
}
setCommand(command) {
this.command = command
}
executeCommand() {
this.command.execute()
}
}
// 使用示例
const receiver = new Receiver()
const concreteCommand = new ConcreteCommand(receiver)
const invoker = new Invoker(concreteCommand)
// 发送请求
invoker.executeCommand()
// 可以以计算商品的价格举例
class Process {
constructor(count, price) {
this.count = count
this.price = price
}
calculate () {
this.basicPrice = this.count * this.price
this.preferential()
this.freight()
if (this.basicPrice < 0) this.basicPrice = 0
console.log(this.basicPrice)
}
freight () {
this.basicPrice += 5
}
preferential () {
this.basicPrice -= 1
}
}
// 满减
class FullReduction extends Process {
constructor(count, price) {
super(count, price)
}
freight () {
if (this.basicPrice > 49) {
this.basicPrice += 3
}
else {
this.basicPrice += 0
}
}
preferential () {
if (this.basicPrice > 200) {
this.basicPrice -= 20
}
if (this.basicPrice > 500) {
this.basicPrice -= 60
}
}
}
class GroupBuy extends Process {
constructor(count, price) {
super(count, price)
}
freight () {
this.basicPrice += 5
}
preferential () {
const discount = 1 - this.count * 0.001
this.basicPrice *= discount > 0.8 ? discount : 0.8
this.basicPrice = Math.round(this.basicPrice)
}
}
new FullReduction(3, 10).calculate()
new FullReduction(4, 10).calculate()
new FullReduction(5, 10).calculate()
new FullReduction(21, 10).calculate()
new FullReduction(49, 10).calculate()
new FullReduction(51, 10).calculate()
new GroupBuy(3, 10).calculate()
new GroupBuy(4, 10).calculate()
new GroupBuy(5, 10).calculate()
new GroupBuy(21, 10).calculate()
new GroupBuy(49, 10).calculate()
new GroupBuy(51, 10).calculate()
function myForEach (array, callback) {
for (let index = 0; index < array.length; index++) {
const item = array[index];
callback(item, index)
}
}
function myMap (array, callback) {
let load = []
for (let index = 0; index < array.length; index++) {
const item = array[index];
load.push(callback(item, index))
}
return load
}
const array = [123, 'abc', null, [4, 5, 6], undefined, { d: 'e' }]
myForEach(array, (item, index) => {
console.log(item, index)
})
const newArray = myMap(array, (item, index) => {
return index
})
console.log(newArray)
class Chain {
constructor(fn) {
this.fn = fn
this.next = null
}
addChain (fn) {
this.next = fn
return this
}
check (value) {
this.fn(value) ? this.next.check(value) : null
}
}
function CheckNull (value) {
if (!value) {
console.log('值不能为空')
return false
}
return true
}
function checkNumber (value) {
if (!isNaN(+value)) {
console.log('必须为数值类型')
return false
}
return true
}
function checkPhone (value) {
const ret = /^1((34[0-8])|(8\d{2})|(([35][0-35-9]|4[579]|66|7[35678]|9[1389])\d{1}))\d{7}$/
if (!ret.test(value)) {
console.log('手机号格式不正确')
return false
}
return true
}
new Chain(CheckNull).addChain(new Chain(checkNumber).addChain(new Chain(checkPhone))).check('')
const strategies = {
"S": function (salary) {
return salary * 4
},
"A": function (salary) {
return salary * 3
},
"B": function (salary) {
return salary * 2
}
}
function calculateBonus (level, salary) {
return strategies[level](salary)
}
持续更新……
可以看看这个,写的还挺好