Skip to content

Instantly share code, notes, and snippets.

@mcustiel
Last active February 9, 2016 15:29
Show Gist options
  • Save mcustiel/a6e6cc0d53c5afe4af16 to your computer and use it in GitHub Desktop.
Save mcustiel/a6e6cc0d53c5afe4af16 to your computer and use it in GitHub Desktop.
Design patterns examples for knowledge sharing session
public class StreetMap {
private final Point origin;
private final Point destination;
private final Color waterColor;
private final Color landColor;
private final Color highTrafficColor;
private final Color mediumTrafficColor;
private final Color lowTrafficColor;
public static class Builder {
// Required parameters
private final Point origin;
private final Point destination;
// Optional parameters - initialize with default values
private Color waterColor = Color.BLUE;
private Color landColor = new Color(30, 30, 30);
private Color highTrafficColor = Color.RED;
private Color mediumTrafficColor = Color.YELLOW;
private Color lowTrafficColor = Color.GREEN;
public Builder(Point origin, Point destination) {
this.origin = origin;
this.destination = destination;
}
public Builder waterColor(Color color) {
waterColor = color;
return this;
}
public Builder landColor(Color color) {
landColor = color;
return this;
}
public Builder highTrafficColor(Color color) {
highTrafficColor = color;
return this;
}
public Builder mediumTrafficColor(Color color) {
mediumTrafficColor = color;
return this;
}
public Builder lowTrafficColor(Color color) {
lowTrafficColor = color;
return this;
}
public StreetMap build() {
return new StreetMap(this);
}
}
private StreetMap(Builder builder) {
// Required parameters
origin = builder.origin;
destination = builder.destination;
// Optional parameters
waterColor = builder.waterColor;
landColor = builder.landColor;
highTrafficColor = builder.highTrafficColor;
mediumTrafficColor = builder.mediumTrafficColor;
lowTrafficColor = builder.lowTrafficColor;
}
}
class Main
{
public static void main(String args[]) {
StreetMap map = new StreetMap.Builder(new Point(50, 50), new Point(100,
100)).landColor(Color.GRAY).waterColor(Color.BLUE.brighter())
.build();
}
}
var Gallery = function (imagesList) {
var images = imagesList;
this.getImages = function () {
return images;
};
this.draw = function () {
// Draws the gallery
};
this.next = function () {
// Moves to next image
};
this.previous = function () {
// Moves to previous image
};
};
// -----------------------------
var AutoSlideDecorator = function (baseGallery, timeInMillis) {
var gallery = baseGallery,
intervalTime = timeInMillis,
startTimeInterval = function () {
// init loop that every $timeInMillis milliseconds go to next image.
};
this.getImages = function () {
return gallery.getImages();
};
this.draw = function () {
gallery.draw();
startTimeInterval();
};
this.next = function () {
gallery.next();
};
this.previous = function () {
gallery.previous();
};
};
// ----------------------------
var ThumbnailsDecorator = function (baseGallery) {
var gallery = baseGallery,
drawThumbnails = function () {
// draw list of thumbnails with each image of the gallery
};
this.getImages = function () {
return gallery.getImages();
};
this.draw = function () {
gallery.draw();
drawThumbnails();
};
this.next = function () {
gallery.next();
};
this.previous = function () {
gallery.previous();
};
};
// ---------------------------------
var images = $(".galleryItem").get(); // Jquery! Mua ha ha ha ha
var gallery = new Gallery(images);
gallery = new AutoSlideDecorator(gallery, 5000);
gallery = new ThumbnailsDecorator(gallery);
gallery.draw();
<?php
class Gallery
{
protected $images = [];
public function __construct(array $images)
{
$this->images = $images;
}
public function draw()
{
// logic to draw the gallery
}
public function next()
{
// logic to show next image
}
public function previous()
{
// logic to show previous image
}
}
// -----------------
class GalleryDecorator extends Gallery
{
private $gallery;
public function __construct(Gallery $gallery)
{
$this->gallery = $gallery;
}
public function draw()
{
$this->gallery->draw();
}
public function next()
{
$this->gallery->next();
}
public function previous()
{
$this->gallery->previous();
}
}
// -----------------------
class AutoSlideDecorator extends GalleryDecorator
{
private $timeInMillis;
public function __construct(Gallery $gallery, $timeInMillis = 1000)
{
parent::__construct($gallery);
$this->timeInMillis = $timeInMillis;
}
public function draw()
{
parent::draw();
$this->startTimeInterval();
}
private function startTimeInterval()
{
// init loop that every $timeInMillis milliseconds go to next image.
}
}
// -----------------------
class ThumbnailsDecorator extends GalleryDecorator
{
public function __construct(Gallery $gallery)
{
parent::__construct($gallery);
}
public function draw()
{
parent::draw();
$this->drawThumbnails();
}
private function drawThumbnails()
{
// draw thumbnails and generate logic to go to current image when clicked
}
}
// -------------------
$images = (new ImagesModel(new DatabaseConnection()))->getAll();
$gallery = new Gallery($images);
$gallery = new AutoSlideDecorator($gallery, 5000);
$gallery = new ThumbnailsDecorator($gallery);
$gallery->draw();
/* Complex parts */
interface CPU {
public void freeze();
public void jump(long position);
public void execute();
}
class ArmCPU implements CPU {
public void freeze() { ... }
public void jump(long position) { ... }
public void execute() { ... }
}
interface Memory {
public void load(long position, byte[] data);
}
class DimmRam implements Memory {
public void load(long position, byte[] data) { ... }
}
interface HardDrive {
public byte[] read(long lba, int size);
}
class SSDHD implements HardDrive {
public byte[] read(long lba, int size) { ... }
}
/* Facade */
class ComputerFacade {
private CPU processor;
private Memory ram;
private HardDrive hd;
public ComputerFacade(CPU processor, Memory ram, HardDrive hd) {
this.processor = processor;
this.ram = ram;
this.hd = hd;
}
public void start() {
processor.freeze();
ram.load(BOOT_ADDRESS, hd.read(BOOT_SECTOR, SECTOR_SIZE));
processor.jump(BOOT_ADDRESS);
processor.execute();
}
}
/* Client */
class Person {
public static void main(String[] args) {
ComputerFacade computer = new ComputerFacade(new ArmCPU(), new DimmRAM(), new SSDHD());
computer.start();
}
}
<?php
// It makes the necessary magic (this was a real comment over the function declaration)
function gandalf(/* a gigantic list of arguments */)
{
// 500+ lines of code
}
<?php
abstract class FootballFan
{
protected function scream($message)
{
echo $message;
}
// update method
abstract public function goal($team);
}
class HamburgSVFan extends FootballFan
{
// update implementation
public function goal($team)
{
if ($team == 'hsv') {
$this->scream('Goooooaaalll!!!!');
}
}
}
class BorussiaDortmundFan extends FootballFan
{
// update implementation
public function goal($team)
{
if ($team == 'bvb') {
$this->scream('Goooooaaalll!!!!');
}
}
}
class Match
{
private $spectators = [];
// attach method
public function addSpectator(FootballFan $fan)
{
$this->spectators[$fan->__toString()] = $fan;
}
// dettach method
public function haveBetterThingsToWatch(FootballFan $fan)
{
unset($this->spectators[$fan->__toString]);
}
// Notify method
public function notify()
{
$team = $this->getLastGoalTeam();
foreach ($this->spectators as $fan) {
$fan->goal($team);
}
}
public function play()
{
$time = 0;
while ($time < 90) {
if ($this->goal()) {
$this->notify();
}
$time++;
}
}
}
// ----------------------------------------
$match = new Match();
$hsvFan = new HamburgSVFan();
$match->addSpectator($hsvFan);
$bvbFan = new BorussiaDortmundFan();
$match->addSpectator($bvbFan);
$match->play();
if ($match->getGoals('bvb') > $match->getGoals('hsv') + 3) {
$match->haveBetterThingsToWatch($hsvFan);
}
import java.util.ArrayList;
import java.util.List;
interface BillingStrategy {
public double getActPrice(double rawPrice);
}
// Normal billing strategy (unchanged price)
class NormalStrategy implements BillingStrategy {
@Override
public double getActPrice(double rawPrice) {
return rawPrice;
}
}
// Strategy for Happy hour (50% discount)
class HappyHourStrategy implements BillingStrategy {
@Override
public double getActPrice(double rawPrice) {
return rawPrice * 0.5;
}
}
class Customer {
private List<Double> drinks;
private BillingStrategy strategy;
public Customer(BillingStrategy strategy) {
this.drinks = new ArrayList<Double>();
this.strategy = strategy;
}
public void add(double price, int quantity) {
drinks.add(strategy.getActPrice(price * quantity));
}
// Payment of bill
public void printBill() {
double sum = 0;
for (Double i : drinks) {
sum += i;
}
System.out.println("Total due: " + sum);
drinks.clear();
}
// Set Strategy
public void setStrategy(BillingStrategy strategy) {
this.strategy = strategy;
}
}
public class Pub {
public static void main(String[] args) {
Customer a = new Customer(new NormalStrategy());
// Normal billing
a.add(1.0, 1);
// Start Happy Hour
a.setStrategy(new HappyHourStrategy());
a.add(1.0, 2);
// New Customer
Customer b = new Customer(new HappyHourStrategy());
b.add(0.8, 1);
// The Customer pays
a.printBill();
// End Happy Hour
b.setStrategy(new NormalStrategy());
b.add(1.3, 2);
b.add(2.5, 1);
b.printBill();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment