php和js制作悬浮窗,php和javascript的设计模式比较(装饰器模式)

PHP:

//装饰者模式

abstract class Beverage{

public $_name;

abstract public function Cost();

}

class Coffee extends Beverage{

public function __construct(){

$this -> _name = 'Coffee';

}

public function Cost(){

return 1.00;

}

}

class CondimentDecorator extends Beverage{

public function __construct(){

$this -> _name = 'Condiment';

}

public function Cost(){

return 0.1;

}

}

class Milk extends CondimentDecorator{

private $_beverage;

public function __construct($beverage){

$this -> _name = 'Milk';

$this -> _beverage = $beverage;

}

public function Cost(){

return $this -> _beverage -> Cost() + 0.2;

}

}

class Sugar extends CondimentDecorator{

private $_beverage;

public function __construct($beverage){

$this -> _name = 'Sugar';

$this -> _beverage = $beverage;

}

public function Cost(){

return $this -> _beverage -> Cost() + 0.3;

}

}

$coffee = new Sugar(new Milk(new Coffee()));

echo $coffee -> Cost();

Javascript:

var Coffee = function(){

this.name = 'Coffee';

this.Cost = function(){

return 1.0;

}

}

var Milk = function(beverage){

this.name = 'Milk';

this.Cost = function(){

return beverage.Cost() + 0.2;

}

}

var Sugar = function(beverage){

this.name = 'Sugar';

this.Cost = function(){

return beverage.Cost() + 0.3;

}

}

var beverage = new Sugar(new Milk(new Coffee()));

console.log(beverage.Cost());

总结:保持原有的接口,并为原来的动态的添加新的功能。增加一个修饰类包裹原来的类,包裹的方式一般是通过在将原来的对象作为修饰类的构造函数的参数。采用了组合对象的方式。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值