The abstract factory pattern is one of five design patterns in the Creational Design Pattern group. The abstract factory provides an interface for creating families of related or dependent objects without specifying their concrete classes.
The abstract factory pattern should be used when a developer wants to:
Platform type:
enum EPlatform { IOS = 'iOS', ANDROID = 'android', }
Platform interface:
interface IPlatform { generateToken(): string; destroyToken(): boolean; }
Implements
export class IosPlatform implements IPlatform { generateToken(): string { return 'iOS Token'; } destroyToken(): boolean { return false; } } export class AndroidPlatform implements IPlatform { generateToken(): string { return 'Android Token'; } destroyToken(): boolean { return true; } }
Factory with a static method:
export class Platform { public static getPlatform(os: EPlatform): IPlatform { switch(os) { case EPlatform.IOS: return new IosPlatform(); case EPlatform.ANDROID: return new AndroidPlatform(); default: throw new Error('Operation system does not support!!!'); } } }
The client code:
function client() { const iOS = Platform.getPlatform(EPlatform.IOS); const android = Platform.getPlatform(EPlatform.ANDROID); console.log('iOS Token:', iOS.generateToken()); console.log('Android Token:', android.generateToken()); console.log('iOS Destroy Token:', iOS.destroyToken()); console.log('Android Destroy Token:', android.destroyToken()); } client();
Result:
iOS Token: iOS Token Android Token: Android Token iOS Destroy Token: false Android Destroy Token: true
Props:
Cons:
Thank you for reading, and happy coding!
I hope this article will help make the concepts of the Abstract Factory Pattern