Skip to content

Instantly share code, notes, and snippets.

@j127
Created November 5, 2013 18:12
Show Gist options
  • Save j127/7323461 to your computer and use it in GitHub Desktop.
Save j127/7323461 to your computer and use it in GitHub Desktop.
Factory Pattern, JavaScript
<!DOCTYPE html>
<html>
<head>
<title>JS Design Patterns</title>
<meta charset="utf-8" />
</head>
<body>
<h1>Factory Pattern</h1>
<button id="buildCar">Build a car</button> <button id="buildMotorbike">Build a motorbike</button>
<div id="output"></div>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$(document).ready(function() {
$('#buildCar').on('click', function() {
console.log('#buildCar button clicked');
var myCar = VehicleFactory.factory('Car');
console.log(myCar);
});
$('#buildMotorbike').on('click', function() {
console.log('#buildMotorbike button clicked');
var myMotorbike = VehicleFactory.factory('Motorbike');
console.log(myMotorbike);
});
});
// Factory pattern
function VehicleFactory() {}
VehicleFactory.factory = function(type) {
var type = type;
var Vehicle;
VehicleFactory[type].prototype = new VehicleFactory();
Vehicle = new VehicleFactory[type]();
return Vehicle;
}
VehicleFactory.Car = function() {
this.doors = 4;
this.maxSpeed = 100;
}
VehicleFactory.Motorbike = function() {
this.doors = 0;
this.maxSpeed = 150;
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment