Skip to content

Instantly share code, notes, and snippets.

@jeanjmichel
Created November 1, 2019 22:24
Show Gist options
  • Save jeanjmichel/8b28e69970a9c7ca4c61f46997a9e66e to your computer and use it in GitHub Desktop.
Save jeanjmichel/8b28e69970a9c7ca4c61f46997a9e66e to your computer and use it in GitHub Desktop.
Of course this is just an example. And the goal here is to show how you can create a factory of objects (even if each object has an unique relevant set of information).
/**
* In this folder (creational.patterns/factory.pattern/) you will find an
* example implementation of the Factory design pattern. This means that
* you will see that things were created without using the word 'new'.
*
* @author Jean J. Michel
*/
class iPhoneFamily {
public version: string;
public suportedIOs: number;
public initialPrice: number;
public headphoneConnectorType: string;
constructor(props: any) {
this.version = props.version;
this.suportedIOs = props.suportedIOs;
this.headphoneConnectorType = props.headphoneConnectorType;
this.initialPrice = props.initialPrice;
}
}
class PixelFamily {
version: string;
suportedAndroid: number;
initialPrice: number;
constructor(props: any) {
this.version = props.version;
this.suportedAndroid = props.suportedAndroid;
this.initialPrice = props.initialPrice;
}
}
class GalaxyFamily {
version: string;
suportedAndroid: number;
kilotons: number;
initialPrice: number;
constructor(props: any) {
this.version = props.version;
this.suportedAndroid = props.suportedAndroid;
this.kilotons = props.kilotons;
this.initialPrice = props.initialPrice;
}
}
/**
* This method returns an instance of an specific class, but the method is
* agnostic and can returns any known kind of smartphone class.
* @author Jean J. Michel
*/
export class SmartphoneFactory {
public static getSmartphone(model: string, props: any) {
let models = new Map();
models.set('iPhoneFamily', iPhoneFamily);
models.set('PixelFamily', PixelFamily);
models.set('GalaxyFamily', GalaxyFamily);
const createInstanceOf = models.get(model)
return new createInstanceOf(props);
}
}
@jeanjmichel
Copy link
Author

A way to use is:

import { SmartphoneFactory } from './design.patterns/creational.patterns/factory.pattern/factory.pattern'

const iPhoneXR = SmartphoneFactory.getSmartphone('iPhoneFamily', {version: 'iPhone XR', suportedIOs: 13, headphoneConnectorType: "Lightning", initialPrice: 999.90});
const pixelXL = SmartphoneFactory.getSmartphone('PixelFamily', {version: 'Pixel XL', suportedAndroid: 7.1, initialPrice: 600});
const galaxyNote7 = SmartphoneFactory.getSmartphone('GalaxyFamily', {version: 'Galaxy Note 7', suportedAndroid: 6, kilotons: 7, initialPrice: 30});

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