您的位置:首页 > Web前端 > JavaScript

javascript模式 (3)——工厂模式和装饰模式

2015-08-25 08:52 716 查看
上节我们讲解了单例模式,这节我们将继续讲解工厂模式和迭代器模式

工厂模式:

工厂模式的目的是为了方便的创建对象(可以在不知道构造的情况下),通过静态方法来实现,在java或c#等静态编译语言中需要通过反射实现,而javascript这一切会很简单,利用索引访问方法特性,如Coffee[coffeeType]();

var Coffee = function (name,price) {
this.name = name;
this.price = price;
}
Coffee.createCoffee = function (coffeeType) {
if (typeof Coffee[coffeeType] != 'function') {
throw Error('没有此种类型咖啡');
}
return  Coffee[coffeeType]();
}
Coffee.mocha = function () {
return new Coffee('MochaCoffee', 20);
}
Coffee.blue = function () {
return new Coffee('BlueCoffee', 30);
}
module.exports = Coffee;


var blueCoffee =   Coffee.createCoffee('blue');
console.log(blueCoffee.name === 'BlueCoffee');


通过静态方法创建各种类型coffee实现,然后在工厂方法(createCoffee)中通过索引调用相应的方法并返回对象,在代码编写过程中最重要的是将方法名和方法的实际含义关联起来,这样再创建时才可以正确快速的找到需要的类型。

装饰模式:

装饰模式是一种非常实用的模式,本质是一种对象的组合,手机话费构成是典型的装饰模式,话费一般由基础套餐(N个)和特色套餐(m个)构成,不做处理的情况下用户套餐可能需要n*m个对象才能描述,很显然没人会这样做,人们需要的是一个N+M的组合方式。

首先定义基础套餐类,基础套餐采用之前介绍的工厂模式创建,预置了几种套餐类型:

var BasePackage = function (price, description) {

this.price = Number(price);
this.description = description;

BasePackage.prototype.getDescription = function () {
return '您的套餐:' + this.description + '每月' + this.price;
}
}

BasePackage.create = function (packageType) {
if (typeof BasePackage[packageType] != "function") {
throw Error('没有这样的套餐');
}
return BasePackage[packageType]();
}

BasePackage.home = function () {
return new BasePackage('50', '基础套餐');
}

BasePackage.business = function () {
return new BasePackage('100', '商务套餐');
}

BasePackage.ultimate = function () {
return new BasePackage('150', '旗舰套餐');
}


接着创建特色套餐,同样采用工厂模式,也同样预置几种套餐类型

var FeaturePackage = function (price, description) {

this.price = Number(price);
this.description = description;
}

FeaturePackage.create = function (packageType) {
if (typeof FeaturePackage[packageType] != "function") {
throw Error('没有这样的套餐');
}
return FeaturePackage[packageType]();
}

FeaturePackage.traffic = function () {
return new FeaturePackage('20', '流量套餐');
}

FeaturePackage.sms = function () {
return new FeaturePackage('10', '短信套餐');
}


需要将特色套餐装饰到基础套餐类中从而实现各种套餐组合,在基础套餐类定义装饰方法:

BasePackage.prototype.decorate= function(decorate) {
var featurePackage = FeaturePackage.create(decorate);
this.price += featurePackage.price;
this.description += ' + ' + featurePackage.description;
}


最后在搭配套餐的时候只需要选择想要的基础套餐和特色套餐装饰起来即可:

var basePackage = BasePackage.create('home');
basePackage.decorate('sms');
console.log(basePackage.getDescription());


小结:

本节讲解了工厂和装饰模式,并将两种模式融合在一起组成了一个手机套餐实例,工厂模式可以代替new操作,而装饰模式可以将对象进行组合从而实现代码的复用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: