在食堂吃饭,没筷子怎么行?我是从来不带饭盆的。师傅很人性化,每个窗口都放着一大把筷子,随用随拿。
这个模式如果用好,有的地方可以很省力。比如,我网站里的滚动条:
//ScrollBar.as
//滚动条组件
class ScrollBar extends BaseMovie {
var BgLength:Number;
var BlockLength:Number;
var mcBlock:MovieClip
var Width:Number;
var ScrollType;
var scrollTxt:TextField;
var scrollMc:MovieClip;
var McHeight:Number
var initialY:Number
function ScrollBar() {
}
function InitialScrollBar(BgLength, BlockLength) {
this.BlockLength = BlockLength;
this.BgLength = BgLength;
}
function BindTo(mc,type:String,intMcHeight:Number,yinitial:Number){
ScrollType=type;
if(type=="TXT"){
scrollTxt=mc;
}
if(type=="MC"){
initialY=yinitial;
McHeight=intMcHeight;
scrollMc=mc;
}
}
function Scroll() {
if(ScrollType=="TXT")
this.onEnterFrame = function() {
scrollTxt.scroll = scrollTxt.maxscroll*mcBlock._y/(BgLength-BlockLength*3/2)
};
if(ScrollType=="MC"){
this.onEnterFrame=function(){
if(scrollMc._height>McHeight){
scrollMc._y = initialY - (scrollMc._height - McHeight) * mcBlock._y / (BgLength - BlockLength * 3 / 2)
}
}
}
}
function ScrollMc() {
}
function StopScroll() {
this.onEnterFrame=null;
}
function Reset(){
mcBlock._y=0;
}
}
//滚动条组件
class ScrollBar extends BaseMovie {
var BgLength:Number;
var BlockLength:Number;
var mcBlock:MovieClip
var Width:Number;
var ScrollType;
var scrollTxt:TextField;
var scrollMc:MovieClip;
var McHeight:Number
var initialY:Number
function ScrollBar() {
}
function InitialScrollBar(BgLength, BlockLength) {
this.BlockLength = BlockLength;
this.BgLength = BgLength;
}
function BindTo(mc,type:String,intMcHeight:Number,yinitial:Number){
ScrollType=type;
if(type=="TXT"){
scrollTxt=mc;
}
if(type=="MC"){
initialY=yinitial;
McHeight=intMcHeight;
scrollMc=mc;
}
}
function Scroll() {
if(ScrollType=="TXT")
this.onEnterFrame = function() {
scrollTxt.scroll = scrollTxt.maxscroll*mcBlock._y/(BgLength-BlockLength*3/2)
};
if(ScrollType=="MC"){
this.onEnterFrame=function(){
if(scrollMc._height>McHeight){
scrollMc._y = initialY - (scrollMc._height - McHeight) * mcBlock._y / (BgLength - BlockLength * 3 / 2)
}
}
}
}
function ScrollMc() {
}
function StopScroll() {
this.onEnterFrame=null;
}
function Reset(){
mcBlock._y=0;
}
}
核心函数是BindTo(),把这个滚动条的实例绑定到某个动态文本框或者某个mc上,就可以实现滚动。
备注:装饰模式的思想是,在不影响其他对象的情况下,以动态,透明的方式给单个对象添加职责。
装饰者模式应该注意的方面:
1、装饰者和被装饰者一定要是一样的类型,也就是说要有一样的超类。在这里,使用继承达到“类型匹配”,而不是通过继承获得“行为” ————装饰器模式
2、装饰器模式:动态的将责任附加到对象上。若要扩展功能,装饰者提供了比继承更有弹性的替代方案。
3、设计原则:类应该对扩展开放,对修改关闭。