Skip to content

Instantly share code, notes, and snippets.

@m-x-k
Last active April 8, 2018 01:22
Show Gist options
  • Save m-x-k/8e73a67c8e786f999af7f3358c8cbafd to your computer and use it in GitHub Desktop.
Save m-x-k/8e73a67c8e786f999af7f3358c8cbafd to your computer and use it in GitHub Desktop.
Create circles with Factory Pattern javascript
(function(win, $) {
var RedCircle = function() {
this.item = $('<div class="circle"></div>');
},
BlueCircle = function() {
this.item = $('<div class="circle" style="background:blue"></div>');
},
CircleFactory = function(color) {
this.create = function(color) {
if (color === 'blue') {
return new BlueCircle();
} else {
return new RedCircle();
}
}
};
var CircleGeneratorSingleton = (function() {
var instance;
function init() {
var _aCircle = [],
_stage = $('.advert'),
_cf = new CircleFactory();
function _position(circle, left, top) {
circle.css('left', left);
circle.css('top', top);
}
function create(left, top, color) {
var circle = _cf.create(color).item;
_position(circle, left, top);
return circle;
}
function add(circle) {
_stage.append(circle);
_aCircle.push(circle);
}
function index() {
return _aCircle.length;
}
return {index: index,
create: create,
add: add};
}
return {
getInstance: function() {
if (!instance) {
instance = init();
}
return instance;
}
}
})();
$(win.document).ready(function() {
$('.advert').click(function(e) {
var cg = CircleGeneratorSingleton.getInstance();
var circle = cg.create(e.pageX, e.pageY, 'red');
cg.add(circle);
});
$(document).keypress(function(e) {
if (e.key == 'a') {
var cg = CircleGeneratorSingleton.getInstance();
var circle = cg.create(Math.floor(Math.random()* 600), Math.floor(Math.random()* 600),'blue');
cg.add(circle);
}
});
});
})(window, jQuery);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="keywords" content="design patterns">
<title>Mastering Javascript</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<style type="text/css" media="screen">
.circle {
position: relative;
border-radius: 50%;
width: 50px;
height: 50px;
background-color: red;
}
</style>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="circleFactory.js"></script>
</head>
<body>
<h1>Circles</h1>
<h3>[Factory Design Pattern]</h3>
<div class="container">
<div class="advert">
Press 'a' for blue circle or click inside here for red circle.
</div>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment