日期:2014-05-16  浏览次数:20433 次

Java, C#, JavaScript三种语言实现工厂模式

工厂模式的思想是:”把实例的创建延迟到子类去

Java版

抽象产品类:

package Factory;

public interface IProduct {
	 void doSomething();
}
具体类1,具体类2:

package Factory;

public class Product1 implements IProduct {

	@Override
	public void doSomething() {
		// TODO Auto-generated method stub
		System.out.println("procduct1 do something!");
	}

}
package Factory;

public class Product2 implements IProduct {

	@Override
	public void doSomething() {
		// TODO Auto-generated method stub
		System.out.println("procduct2 do something!");
	}

}

抽象工厂类

package Factory;

public abstract class AbstractFactory {
	protected abstract IProduct CreateProduct();
	
	public void Operation(){
		CreateProduct().doSomething();
	}
}
具体工厂类1,具体工厂类2

package Factory;

public class ConcreteFactory1 extends AbstractFactory {

	@Override
	protected IProduct CreateProduct() {
		// TODO Auto-generated method stub
		return new Product1();
	}

}
package Factory;

public class ConcreteFactory2 extends AbstractFactory {

	@Override
	protected IProduct CreateProduct() {
		// TODO Auto-generated method stub
		return new Product2();
	}

}
客户端调用:

package Factory;

public class MainTest {
	public static void main(String[] args) {
		AbstractFactory foctory= new ConcreteFactory1();
		foctory.Operation();
	}
}
C#版,和java类似,省略。

JS版:

/*假如我们想在网页面里插入一些元素,而这些元素类型不固定,可能是图片,也有可能是连接,
 *甚至可能是文本,根据工厂模式的定义,我们需要定义工厂类和相应的子类,
 *我们先来定义子类的具体实现(也就是子函数):*/
var page = page || {};
page.dom = page.dom || {};
// 处理子文本
page.dom.Text = function() {
    this.insert = function(where) {
        var txt = document.createTextNode(this.Url);
        where.appendChild(txt);
    }
}
//子函数2:处理链接
page.dom.Link = function() {
    this.insert = function(where) {
        var link = document.createElement('a');
        link.href = this.url;
        link.appendChild(document.createTextNode(this.url));
        where.appendChild(link);
    };
};

//子函数3:处理图片
page.dom.Image = function() {
    this.insert = function(where) {
        var im = document.createElement('img');
        im.src = this.url;
        where.appendChild(im);
    };
};

// 工厂方法
page.dom.factory = function(type) {
    return new page.dom[type];
}
// 调用
page.dom.client = function() {
    var o = page.dom.factory('Link');
    o.url = 'http://www.cnblogs.com';
    o.insert(document.body);
}