首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件开发 >

Builder - 创建人模式

2013-02-17 
Builder - 创建者模式对于Builder模式很简单,但是一直想不明白为什么要这么设计,为什么要向builder要Produ

Builder - 创建者模式

对于Builder模式很简单,但是一直想不明白为什么要这么设计,为什么要向builder要Product而不是向知道建造过程的Director要。刚才google到一篇文章,总算清楚了。在这里转贴一下这位richardluo的比喻。

简单地说,就好象我要一座房子住,可是我不知道怎么盖(简单的砌墙,层次较低),也不知道怎么样设计(建几个房间,几个门好看,层次较 高),于是我需要找一帮民工,他们会砌墙,还得找个设计师,他知道怎么设计,我还要确保民工听设计师的领导,而设计师本身也不干活,光是下命令,这里砌一 堵墙,这里砌一扇门,这样民工开始建设,最后,我可以向民工要房子了。在这个过程中,设计师是什么也没有,除了他在脑子里的设计和命令,所以要房子也是跟 民工要,记住了!

以下是richardluo的代码,我根据他的思路加上了相应的注释。

1,定义工人接口,就是能够完成建造房子任务的人的通用要求。

// 工人接口,定义了各个工人所要进行的工所作。他们负责进行具体部件如窗户,地板的建造。 // 同时因为房子是民工建的,因此建设完成后由他把房子递交回房主 public interface Builder { public void makeWindow(); public void makeFloor(); public Room getRoom(); } ?2,定义设计师,他的职责是指挥房主指派给他的工人按照自己的设计意图建造房子。
// 设计师。他知道房子应该怎么设计,但他不会自己去建造,而是指挥民工去建造。 public class Designer { // 指挥民工进行工作 public void order(Builder builder) { builder.makeWindow(); builder.makeFloor(); } } ?3,民工,他负责具体事物的实施。
// 民工。负责进行具体部件如窗户,地板的建造。//同时因为房子是?ion.protocol + "//" + location.host + location.pathname + location.search; pre.writeAttribute('codeable_id', post_id); pre.writeAttribute('codeable_type', "Blog"); pre.writeAttribute('source_url', source_url); pre.writeAttribute('pre_index', index); pre.writeAttribute('title', 'Builder - 创建者模式'); }); fix_image_size($$('div.blog_content img'), 700); function processComment() { $$('#main .blog_comment > div').each(function(comment){// comment var post_id = comment.id.substr(2); $$("#"+comment.id+" pre[name=code]").each(function(pre, index){ var location = window.location; source_url = location.protocol + "//" + location.host + location.pathname + location.search; source_url += "#" + comment.id; pre.writeAttribute('codeable_id', post_id); pre.writeAttribute('codeable_type', "BlogComment"); pre.writeAttribute('source_url', source_url); pre.writeAttribute('pre_index', index); pre.writeAttribute('title', 'Builder - 创建者模式'); }); }); } function quote_comment(id) { new Ajax.Request('/editor/quote', { parameters: {'id':id, 'type':'BlogComment'}, onSuccess:function(response){editor.bbcode_editor.textarea.insertAfterSelection(response.responseText); Element.scrollTo(editor.bbcode_editor.textarea.element);} }); } code_favorites_init(); processComment(); new WeiboShare({share_buttons: $('share_weibo'), img_scope: $('blog_content')});

热点排行