The factory pattern consists of a collection of objects, a factory, and a client that requires instances of the objects. The client controls the process, but is decoupled from the actual construction of the objects. Makes it easy to extend new types of objects

Step 1: Page – mediaFactory.js


// The factory pattern consists of a collection of objects, a factory, and a client that requires instances of the objects.  The client controls the process, but is decoupled from the actual construction of the objects.  Makes it easy to extend new types of objects
define(function (require) {
	'use strict';
	
	var media = {
		Video: require('factory/video'),
		Image: require('factory/image')	
	};
	
	return {
		createMedia: function (type, attributes) {
			var MediaType = media[type];
			
			return new MediaType(attributes);	
		}
	};
});

Step 2: Page – image.js


// We are working with a factory pattern right now.  Factory patterns are creational patterns that can wrap a constructor so that it returns instances of objects.  It is used often in JS to simplify the creation of complex objects and to create a large number of similar objects
define(function () {
	'use strict';
	
	var Image = function (attributes) {
		this.width = attributes.width || 0;
		this.height = attributes.height || 0;
		this.name = attributes.name || '';
	};
	
	return Image;
});

Step 3: Page – video.js


// We are working with a factory pattern right now.  Factory patterns are creational patterns that can wrap a constructor so that it returns instances of objects.  It is used often in JS to simplify the creation of complex objects and to create a large number of similar objects
define(function () {
	'use strict';
	
	var Video = function (attributes) {
		this.length = attributes.length || 0;
		this.name = attributes.name || '';
	};
	
	return Video;
});

Step 4: Page – main.js


// JavaScript Document
require (
	['factory/init', 'pubSub/init', 'strategy/init', 'observer/init'],
	function (factory) {
			'use strict';
	
			var examples = {
					factory: factory
				};
			
			window.runExample = function (example) {
				examples[example].init();
			};
	}
);

Step 4: Page – init.js


define(function(require) {
	'use strict';

	return {
		init: function() {
			
			var myVideo, myImage,
				mediaFactory = require('factory/mediaFactory');
				
				myVideo = mediaFactory.createMedia('Video', {
					length: 3.5,
					name: 'My video'
				});
				
				myImage = mediaFactory.createMedia('Image', {
					width: 100,
					height: 11,
					name: 'My Image'
				});
				
				console.log(myVideo);
				console.log(myImage);
		}
	};
});

Leave a Reply