前端常见的设计模式主要有以下几种:
1. 单例模式
2. 工厂模式
3. 策略模式
4. 代理模式
5. 观察者模式
6. 模块模式
7. 构造函数模式
8. 混合模式
var single = (function(){
let instance;
function getInstance(){
// 如果该实例存在,则直接返回,否则就对其实例化
if( instance=== undefined ){
instance= new Construct();
}
return instance;
}
function Construct(){
// ... 生成单例的构造函数的代码
}
return {
getInstance : getInstance
}
})();
//安全模式创建的工厂方法函数
let UserFactory = function(role) {
if(this instanceof UserFactory) {
var s = new this[role]();
return s;
} else {
return new UserFactory(role);
}
}
//工厂方法函数的原型中设置所有对象的构造函数
UserFactory.prototype = {
SuperAdmin: function() {
this.name = "超级管理员",
this.viewPage = ['首页', '通讯录', '发现页', '应用数据', '权限管理']
},
Admin: function() {
this.name = "管理员",
this.viewPage = ['首页', '通讯录', '发现页', '应用数据']
},
NormalUser: function() {
this.name = '普通用户',
this.viewPage = ['首页', '通讯录', '发现页']
}
}
//调用
let superAdmin = UserFactory('SuperAdmin');
let admin = UserFactory('Admin')
let normalUser = UserFactory('NormalUser')
// 对于vip客户
function vipPrice() {
this.discount = 0.5;
}
vipPrice.prototype.getPrice = function(price) {
return price * this.discount;
}
// 对于老客户
function oldPrice() {
this.discount = 0.3;
}
oldPrice.prototype.getPrice = function(price) {
return price * this.discount;
}
// 对于普通客户
function Price() {
this.discount = 1;
}
Price.prototype.getPrice = function(price) {
return price ;
}
// 上下文,对于客户端的使用
function Context() {
this.name = '';
this.strategy = null;
this.price = 0;
}
Context.prototype.set = function(name, strategy, price) {
this.name = name;
this.strategy = strategy;
this.price = price;
}
Context.prototype.getResult = function() {
console.log(this.name + ' 的结账价为: ' + this.strategy.getPrice(this.price));
}
var context = new Context();
var vip = new vipPrice();
context.set ('vip客户', vip, 200);
context.getResult(); // vip客户 的结账价为: 100
var old = new oldPrice();
context.set ('老客户', old, 200);
context.getResult(); // 老客户 的结账价为: 60
var Price = new Price();
context.set ('普通客户', Price, 200);
context.getResult(); // 普通客户 的结账价为: 200
(function(){
// 目标对象,是真正被代理的对象
function Subject(){}
Subject.prototype.request = function(){};
function Proxy(realSubject){
this.realSubject = realSubject;
}
Proxy.prototype.request = function(){
this.realSubject.request();
};
})();
var EventCenter = (function(){
var events = {};
function on(event, handler){
events[event] = events[event] || [];
events[event].push({
handler: handler
});
}
function fire(event, args){
if (!events[event]) {return}
for (var i = 0; i < events[event].length; i++) {
events[event][i].handler(args);
}
}
function off(event){
delete events[event];
}
return {
on: on,
fire: fire,
off: off
}
})();
EventCenter.on('event', function(data){
console.log('event received...');
});
var Person = (function() {
var name = 'xxx'
function sayName() {
console.log(name)
}
return{
name: name,
sayName: sayName
}
})()