工厂模式
Posted 起个好名字
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了工厂模式相关的知识,希望对你有一定的参考价值。
1 <!DOCTYPE html> 2 <html> 3 4 <head> 5 <meta charset="UTF-8"> 6 <title></title> 7 </head> 8 9 <body> 10 <script> 11 var DomFactory = (function(){ 12 this.Link = function(){ 13 this.appendTo = function(target){ 14 var ele = document.createElement("link"); 15 ele.url = this.url; 16 target.appendChild(ele); 17 } 18 } 19 this.Img = function(){ 20 this.appendTo = function(target){ 21 var ele = document.createElement("img"); 22 ele.src = this.src; 23 target.appendChild(ele); 24 } 25 } 26 this.Div = function(){ 27 this.appendTo = function(target){ 28 var ele = document.createElement("div"); 29 ele.style = "position:absolute;color:red"; 30 ele.innerHTML = this.text; 31 target.appendChild(ele); 32 } 33 } 34 this.Input = function(){ 35 this.appendTo = function(target){ 36 var ele = document.createElement("input"); 37 ele.type = this.type || "text"; 38 ele.value = this.value; 39 target.appendChild(ele); 40 } 41 } 42 this.create = function(type){ 43 return new this[type]; 44 } 45 return this; 46 })(); 47 window.onload = function(){ 48 var _input = DomFactory.create("Input"); 49 _input.value = "hello"; 50 _input.appendTo(document.body); 51 52 var _div = DomFactory.create("Div"); 53 _div.text = "hehehe"; 54 _div.appendTo(document.body); 55 } 56 57 </script> 58 </body> 59 60 </html>
以上是关于工厂模式的主要内容,如果未能解决你的问题,请参考以下文章
设计模式简单工厂模式 ( 简介 | 适用场景 | 优缺点 | 代码示例 )