Skip to content

Instantly share code, notes, and snippets.

@zD98
Created March 19, 2016 01:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zD98/e5fb3df8788345d716e1 to your computer and use it in GitHub Desktop.
Save zD98/e5fb3df8788345d716e1 to your computer and use it in GitHub Desktop.
设计模式-工厂模式

##Factory模式 ###总结 提供一个通用的接口来创造对象 ###例子 eg function Car(options){} function Truck(options){}

function VehicleFactory() {}

VehicleFactory.prototype.vehicleClass = car;
VehicleFactory.prototype.createVehicle = function(options){
	if(options.vehicleClass = "Car"){
		this.vehicleClass = Car;
	}else {
		this.vehicleClass = Truck;
	}
	return new this.vehicleClass(options);
}

###分析 何时需要Factory 1. 当对象或组件涉及高复杂性时 2. 当需要根据所在的不同环境轻松生成对象的不同实例时 3. 当处理很多共享相同属性的小型对象和组件时 4. 在编写只需要满足一个AP契约(鸭子类型)的其他对象的实例对象 何时不需要Factory 1. 带来大量不必要的复杂性

##Abstract Factory(*/不会用) ###总结 用于封装一组具有共同目标的单个工厂, 能够将一组对象的实现细节从一般用法分离出来 ###例子 eg var AbstractVehicleFactory = (function(){ var types = {}; retrurn { getVehicle: function (type, customizations){ var Vehicle = types[type]; return (Vehicle)? return new Vehicle(customizations):null; }, registerVehicle : function (type, Vehicle) { var proto = Vehicle.prototype; if(proto.drive&&proto.breakDown){ types[type] = Vehicle; } return AbstractVehicleFactory ; } }

})();

###分析 1. 一个系统必须独立于它所创建的对象的生成方法 2. 它需要与多种对象类型一起工作

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment