From 996f5691aef42b270f39f6c4682b177303ed25b4 Mon Sep 17 00:00:00 2001 From: Mark Torok Date: Sat, 22 Oct 2016 13:41:04 +0200 Subject: [PATCH] Add demos --- README.md | 114 ++++++------- adapter/adapter.ts | 45 +++--- adapter/demo.ts | 10 ++ bridge/bridge.ts | 113 ++++++------- bridge/demo.ts | 14 ++ .../chainOfResponsibility.ts | 132 +++++++-------- chain_of_responsibility/demo.ts | 29 ++++ command/command.ts | 132 +++++++-------- command/demo.ts | 17 ++ composite/composite.ts | 111 ++++++------- composite/demo.ts | 25 +++ decorator/decorator.ts | 102 ++++++------ decorator/demo.ts | 12 ++ facade/demo.ts | 13 ++ facade/facade.ts | 89 +++++----- factory_method/demo.ts | 1 - flyweight/demo.ts | 15 ++ flyweight/flyweight.ts | 99 ++++++------ interpreter/demo.ts | 27 ++++ interpreter/interpreter.ts | 61 +++---- iterator/demo.ts | 16 ++ iterator/iterator.ts | 103 ++++++------ main.ts | 113 +++++++++++++ mediator/demo.ts | 18 +++ mediator/mediator.ts | 137 +++++++--------- memento/demo.ts | 16 ++ memento/memento.ts | 149 ++++++++--------- observer/demo.ts | 17 ++ observer/observer.ts | 153 ++++++++---------- proxy/demo.ts | 18 +++ proxy/proxy.ts | 79 ++++----- singleton/spec/singleton.spec.js | 25 --- singleton/src/demo.ts | 1 - state/demo.ts | 18 +++ state/state.ts | 95 +++++------ strategy/demo.ts | 19 +++ strategy/strategy.ts | 83 +++++----- template_method/demo.ts | 14 ++ template_method/templateMethod.ts | 108 ++++++------- tsconfig.json | 33 +++- visitor/demo.ts | 19 +++ visitor/visitor.ts | 151 ++++++++--------- 42 files changed, 1388 insertions(+), 1158 deletions(-) create mode 100644 adapter/demo.ts create mode 100644 bridge/demo.ts create mode 100644 chain_of_responsibility/demo.ts create mode 100644 command/demo.ts create mode 100644 composite/demo.ts create mode 100644 decorator/demo.ts create mode 100644 facade/demo.ts create mode 100644 flyweight/demo.ts create mode 100644 interpreter/demo.ts create mode 100644 iterator/demo.ts create mode 100644 main.ts create mode 100644 mediator/demo.ts create mode 100644 memento/demo.ts create mode 100644 observer/demo.ts create mode 100644 proxy/demo.ts delete mode 100644 singleton/spec/singleton.spec.js create mode 100644 state/demo.ts create mode 100644 strategy/demo.ts create mode 100644 template_method/demo.ts create mode 100644 visitor/demo.ts diff --git a/README.md b/README.md index cb854ff..2ec3a5b 100644 --- a/README.md +++ b/README.md @@ -1,57 +1,57 @@ -# Design Patterns in TypeScript # - -Here are the implementations of the following design patterns in TypeScript: - -### Creational ### - -* [Singleton](https://github.com/torokmark/design_patterns_in_typescript/tree/master/singleton) -* [Abstract Factory](https://github.com/torokmark/design_patterns_in_typescript/tree/master/abstract_factory) -* [Factory Method](https://github.com/torokmark/design_patterns_in_typescript/tree/master/factory_method) -* [Builder](https://github.com/torokmark/design_patterns_in_typescript/tree/master/builder) -* [Prototype](https://github.com/torokmark/design_patterns_in_typescript/tree/master/prototype) - - -### Structural Patterns ### - -* [Adapter](https://github.com/torokmark/design_patterns_in_typescript/tree/master/adapter) -* [Bridge](https://github.com/torokmark/design_patterns_in_typescript/tree/master/bridge) -* [Composite](https://github.com/torokmark/design_patterns_in_typescript/tree/master/composite) -* [Decorator](https://github.com/torokmark/design_patterns_in_typescript/tree/master/decorator) -* [Facade](https://github.com/torokmark/design_patterns_in_typescript/tree/master/facade) -* [Flyweight](https://github.com/torokmark/design_patterns_in_typescript/tree/master/flyweight) -* [Proxy](https://github.com/torokmark/design_patterns_in_typescript/tree/master/proxy) - - -### Behavioral Patterns ### - -* [Chain of Responsibility](https://github.com/torokmark/design_patterns_in_typescript/tree/master/chain_of_responsibility) -* [Command](https://github.com/torokmark/design_patterns_in_typescript/tree/master/command) -* [Interpreter](https://github.com/torokmark/design_patterns_in_typescript/tree/master/interpreter) -* [Iterator](https://github.com/torokmark/design_patterns_in_typescript/tree/master/iterator) -* [Mediator](https://github.com/torokmark/design_patterns_in_typescript/tree/master/mediator) -* [Memento](https://github.com/torokmark/design_patterns_in_typescript/tree/master/memento) -* [Observer](https://github.com/torokmark/design_patterns_in_typescript/tree/master/observer) -* [State](https://github.com/torokmark/design_patterns_in_typescript/tree/master/state) -* [Strategy](https://github.com/torokmark/design_patterns_in_typescript/tree/master/strategy) -* [Template Method](https://github.com/torokmark/design_patterns_in_typescript/tree/master/template_method) -* [Visitor](https://github.com/torokmark/design_patterns_in_typescript/tree/master/visitor) - -## Compile the project - -``` -$ git clone https://github.com/torokmark/design_patterns_in_typescript.git -$ cd design_patterns_in_typescript -$ tsc -``` - -There is a new `tsconfig.json` file in the root direcotry which is responsible for the compiler options. -As it is set the default target is Ecmascript5 now. -Any additional options come here. - -To compile only one pattern, use the following command. - -``` -$ cd design_patterns_in_typescript/visitor -$ tsc --target ES5 visitor.ts -``` -> Here if there is no `--outFile` option then the compiler generates the js counterpart into the current directory. +# Design Patterns in TypeScript # + +Here are the implementations of the following design patterns in TypeScript: + +### Creational ### + +* [Singleton](https://github.com/torokmark/design_patterns_in_typescript/tree/master/singleton) +* [Abstract Factory](https://github.com/torokmark/design_patterns_in_typescript/tree/master/abstract_factory) +* [Factory Method](https://github.com/torokmark/design_patterns_in_typescript/tree/master/factory_method) +* [Builder](https://github.com/torokmark/design_patterns_in_typescript/tree/master/builder) +* [Prototype](https://github.com/torokmark/design_patterns_in_typescript/tree/master/prototype) + + +### Structural Patterns ### + +* [Adapter](https://github.com/torokmark/design_patterns_in_typescript/tree/master/adapter) +* [Bridge](https://github.com/torokmark/design_patterns_in_typescript/tree/master/bridge) +* [Composite](https://github.com/torokmark/design_patterns_in_typescript/tree/master/composite) +* [Decorator](https://github.com/torokmark/design_patterns_in_typescript/tree/master/decorator) +* [Facade](https://github.com/torokmark/design_patterns_in_typescript/tree/master/facade) +* [Flyweight](https://github.com/torokmark/design_patterns_in_typescript/tree/master/flyweight) +* [Proxy](https://github.com/torokmark/design_patterns_in_typescript/tree/master/proxy) + + +### Behavioral Patterns ### + +* [Chain of Responsibility](https://github.com/torokmark/design_patterns_in_typescript/tree/master/chain_of_responsibility) +* [Command](https://github.com/torokmark/design_patterns_in_typescript/tree/master/command) +* [Interpreter](https://github.com/torokmark/design_patterns_in_typescript/tree/master/interpreter) +* [Iterator](https://github.com/torokmark/design_patterns_in_typescript/tree/master/iterator) +* [Mediator](https://github.com/torokmark/design_patterns_in_typescript/tree/master/mediator) +* [Memento](https://github.com/torokmark/design_patterns_in_typescript/tree/master/memento) +* [Observer](https://github.com/torokmark/design_patterns_in_typescript/tree/master/observer) +* [State](https://github.com/torokmark/design_patterns_in_typescript/tree/master/state) +* [Strategy](https://github.com/torokmark/design_patterns_in_typescript/tree/master/strategy) +* [Template Method](https://github.com/torokmark/design_patterns_in_typescript/tree/master/template_method) +* [Visitor](https://github.com/torokmark/design_patterns_in_typescript/tree/master/visitor) + +## Compile the project + +``` +$ git clone https://github.com/torokmark/design_patterns_in_typescript.git +$ cd design_patterns_in_typescript +$ tsc +``` + +There is a new `tsconfig.json` file in the root directory which is responsible for the compiler options. +As it is set the default target is Ecmascript5 now. +Any additional options come here. + +To compile only one pattern, use the following command. + +``` +$ cd design_patterns_in_typescript/visitor +$ tsc --target ES5 visitor.ts +``` +> Here if there is no `--outFile` option then the compiler generates the js counterpart into the current directory. diff --git a/adapter/adapter.ts b/adapter/adapter.ts index a233bcc..633ea9d 100644 --- a/adapter/adapter.ts +++ b/adapter/adapter.ts @@ -1,25 +1,20 @@ -namespace AdapterPattern { - - export class Adaptee { - public method(): void { - console.log("`method` of Adaptee is being called"); - } - } - - export interface Target { - call(): void; - } - - export class Adapter implements Target { - public call(): void { - console.log("Adapter's `call` method is being called"); - var adaptee: Adaptee = new Adaptee(); - adaptee.method(); - } - } -} - -(function main() { - var adapter: AdapterPattern.Adapter = new AdapterPattern.Adapter(); - adapter.call(); -}()); \ No newline at end of file +namespace AdapterPattern { + + export class Adaptee { + public method(): void { + console.log("`method` of Adaptee is being called"); + } + } + + export interface Target { + call(): void; + } + + export class Adapter implements Target { + public call(): void { + console.log("Adapter's `call` method is being called"); + var adaptee: Adaptee = new Adaptee(); + adaptee.method(); + } + } +} diff --git a/adapter/demo.ts b/adapter/demo.ts new file mode 100644 index 0000000..7c18f9f --- /dev/null +++ b/adapter/demo.ts @@ -0,0 +1,10 @@ +/// +namespace AdapterPattern { + export namespace Demo { + + export function show() : void { + var adapter: AdapterPattern.Adapter = new AdapterPattern.Adapter(); + adapter.call(); + } + } +} diff --git a/bridge/bridge.ts b/bridge/bridge.ts index bd1ed09..ba7c001 100644 --- a/bridge/bridge.ts +++ b/bridge/bridge.ts @@ -1,60 +1,53 @@ -namespace BridgePattern { - - export class Abstraction { - implementor: Implementor; - constructor(imp: Implementor) { - this.implementor = imp; - } - - public callIt(s: String): void { - throw new Error("This method is abstract!"); - } - } - - export class RefinedAbstractionA extends Abstraction { - constructor(imp: Implementor) { - super(imp); - } - - public callIt(s: String): void { - console.log("This is RefinedAbstractionA"); - this.implementor.callee(s); - } - } - - export class RefinedAbstractionB extends Abstraction { - constructor(imp: Implementor) { - super(imp); - } - - public callIt(s: String): void { - console.log("This is RefinedAbstractionB"); - this.implementor.callee(s); - } - } - - export interface Implementor { - callee(s: any): void; - } - - export class ConcreteImplementorA implements Implementor { - public callee(s: any) : void { - console.log("`callee` of ConcreteImplementorA is being called."); - console.log(s); - } - } - - export class ConcreteImplementorB implements Implementor { - public callee(s: any) : void { - console.log("`callee` of ConcreteImplementorB is being called."); - console.log(s); - } - } -} - -(function main() { - var abstractionA: BridgePattern.Abstraction = new BridgePattern.RefinedAbstractionA(new BridgePattern.ConcreteImplementorA()); - var abstractionB: BridgePattern.Abstraction = new BridgePattern.RefinedAbstractionB(new BridgePattern.ConcreteImplementorB()); - abstractionA.callIt("abstractionA"); - abstractionB.callIt("abstractionB"); -}()); \ No newline at end of file +namespace BridgePattern { + + export class Abstraction { + implementor: Implementor; + constructor(imp: Implementor) { + this.implementor = imp; + } + + public callIt(s: String): void { + throw new Error("This method is abstract!"); + } + } + + export class RefinedAbstractionA extends Abstraction { + constructor(imp: Implementor) { + super(imp); + } + + public callIt(s: String): void { + console.log("This is RefinedAbstractionA"); + this.implementor.callee(s); + } + } + + export class RefinedAbstractionB extends Abstraction { + constructor(imp: Implementor) { + super(imp); + } + + public callIt(s: String): void { + console.log("This is RefinedAbstractionB"); + this.implementor.callee(s); + } + } + + export interface Implementor { + callee(s: any): void; + } + + export class ConcreteImplementorA implements Implementor { + public callee(s: any) : void { + console.log("`callee` of ConcreteImplementorA is being called."); + console.log(s); + } + } + + export class ConcreteImplementorB implements Implementor { + public callee(s: any) : void { + console.log("`callee` of ConcreteImplementorB is being called."); + console.log(s); + } + } +} diff --git a/bridge/demo.ts b/bridge/demo.ts new file mode 100644 index 0000000..63e5fd4 --- /dev/null +++ b/bridge/demo.ts @@ -0,0 +1,14 @@ +/// +namespace BridgePattern { + export namespace Demo { + + export function show() : void { + var abstractionA: BridgePattern.Abstraction = new BridgePattern.RefinedAbstractionA(new BridgePattern.ConcreteImplementorA()); + var abstractionB: BridgePattern.Abstraction = new BridgePattern.RefinedAbstractionB(new BridgePattern.ConcreteImplementorB()); + + abstractionA.callIt("abstractionA"); + abstractionB.callIt("abstractionB"); + } + } +} + diff --git a/chain_of_responsibility/chainOfResponsibility.ts b/chain_of_responsibility/chainOfResponsibility.ts index be2d2e0..7717830 100644 --- a/chain_of_responsibility/chainOfResponsibility.ts +++ b/chain_of_responsibility/chainOfResponsibility.ts @@ -1,77 +1,55 @@ -namespace ChainOfResponsibilityPattern { - - export class Handler { - private handler: Handler; - private req: number; - - constructor(req: number) { - this.req = req; - } - - public setHandler(handler: Handler): void { - this.handler = handler; - } - - public operation(msg: string, req: number): void { - if (req <= this.req) { - this.handlerRequest(msg) - } else if (this.handler !== null && this.handler !== undefined) { - this.handler.operation(msg, req); - } - } - - public handlerRequest(msg: string): void { - throw new Error("Abstract method!"); - } - } - - export class ConcreteHandler1 extends Handler { - constructor(req: number) { - super(req); - } - public handlerRequest(msg: string) { - console.log("Message (ConcreteHandler1) :: ", msg); - } - } - - - export class ConcreteHandler2 extends Handler { - constructor(req: number) { - super(req); - } - public handlerRequest(msg: string) { - console.log("Message :: (ConcreteHandler2) ", msg); - } - } - - export class ConcreteHandler3 extends Handler { - constructor(req: number) { - super(req); - } - public handlerRequest(msg: string) { - console.log("Message :: (ConcreteHandler3) ", msg); - } - } -} - -(function main() { - var h1: ChainOfResponsibilityPattern.Handler, - h2: ChainOfResponsibilityPattern.Handler, - h3: ChainOfResponsibilityPattern.Handler, - reqs: number[], - i: number, - max: number; - - reqs = [2, 7, 23, 34, 4, 5, 8, 3]; - - h1 = new ChainOfResponsibilityPattern.ConcreteHandler1(3); - h2 = new ChainOfResponsibilityPattern.ConcreteHandler2(7); - h3 = new ChainOfResponsibilityPattern.ConcreteHandler3(20); - - h1.setHandler(h2); - h2.setHandler(h3); - - for (i = 0, max = reqs.length; i < max; i += 1) { - h1.operation("operation is fired!", reqs[i]); - } -}()); \ No newline at end of file +namespace ChainOfResponsibilityPattern { + + export class Handler { + private handler: Handler; + private req: number; + + constructor(req: number) { + this.req = req; + } + + public setHandler(handler: Handler): void { + this.handler = handler; + } + + public operation(msg: string, req: number): void { + if (req <= this.req) { + this.handlerRequest(msg) + } else if (this.handler !== null && this.handler !== undefined) { + this.handler.operation(msg, req); + } + } + + public handlerRequest(msg: string): void { + throw new Error("Abstract method!"); + } + } + + export class ConcreteHandler1 extends Handler { + constructor(req: number) { + super(req); + } + public handlerRequest(msg: string) { + console.log("Message (ConcreteHandler1) :: ", msg); + } + } + + + export class ConcreteHandler2 extends Handler { + constructor(req: number) { + super(req); + } + public handlerRequest(msg: string) { + console.log("Message :: (ConcreteHandler2) ", msg); + } + } + + export class ConcreteHandler3 extends Handler { + constructor(req: number) { + super(req); + } + public handlerRequest(msg: string) { + console.log("Message :: (ConcreteHandler3) ", msg); + } + } +} diff --git a/chain_of_responsibility/demo.ts b/chain_of_responsibility/demo.ts new file mode 100644 index 0000000..7f83efb --- /dev/null +++ b/chain_of_responsibility/demo.ts @@ -0,0 +1,29 @@ +/// +namespace ChainOfResponsibilityPattern { + export namespace Demo { + + export function show() : void { + var h1: ChainOfResponsibilityPattern.Handler, + h2: ChainOfResponsibilityPattern.Handler, + h3: ChainOfResponsibilityPattern.Handler, + reqs: number[], + i: number, + max: number; + + reqs = [2, 7, 23, 34, 4, 5, 8, 3]; + + h1 = new ChainOfResponsibilityPattern.ConcreteHandler1(3); + h2 = new ChainOfResponsibilityPattern.ConcreteHandler2(7); + h3 = new ChainOfResponsibilityPattern.ConcreteHandler3(20); + + h1.setHandler(h2); + h2.setHandler(h3); + + for (i = 0, max = reqs.length; i < max; i += 1) { + h1.operation("operation is fired!", reqs[i]); + } + + } + } +} + diff --git a/command/command.ts b/command/command.ts index 3d38d14..5c0a87d 100644 --- a/command/command.ts +++ b/command/command.ts @@ -1,66 +1,66 @@ -namespace CommandPattern { - export class Command { - public execute(): void { - throw new Error("Abstract method!"); - } - } - - export class ConcreteCommand1 extends Command { - private receiver: Receiver; - - constructor(receiver: Receiver) { - super(); - this.receiver = receiver; - } - - public execute(): void { - console.log("`execute` method of ConcreteCommand1 is being called!"); - this.receiver.action(); - } - } - - export class ConcreteCommand2 extends Command { - private receiver: Receiver; - - constructor(receiver: Receiver) { - super(); - this.receiver = receiver; - } - - public execute(): void { - console.log("`execute` method of ConcreteCommand2 is being called!"); - this.receiver.action(); - } - } - - export class Invoker { - private commands: Command[]; - - constructor() { - this.commands = []; - } - - public storeAndExecute(cmd: Command) { - this.commands.push(cmd); - cmd.execute(); - } - } - - export class Receiver { - public action(): void { - console.log("action is being called!"); - } - } -} - -(function main() { - var receiver: CommandPattern.Receiver = new CommandPattern.Receiver(), - command1: CommandPattern.Command = new CommandPattern.ConcreteCommand1(receiver), - command2: CommandPattern.Command = new CommandPattern.ConcreteCommand2(receiver), - invoker : CommandPattern.Invoker = new CommandPattern.Invoker(); - - invoker.storeAndExecute(command1); - invoker.storeAndExecute(command2); - -}()); - +namespace CommandPattern { + export class Command { + public execute(): void { + throw new Error("Abstract method!"); + } + } + + export class ConcreteCommand1 extends Command { + private receiver: Receiver; + + constructor(receiver: Receiver) { + super(); + this.receiver = receiver; + } + + public execute(): void { + console.log("`execute` method of ConcreteCommand1 is being called!"); + this.receiver.action(); + } + } + + export class ConcreteCommand2 extends Command { + private receiver: Receiver; + + constructor(receiver: Receiver) { + super(); + this.receiver = receiver; + } + + public execute(): void { + console.log("`execute` method of ConcreteCommand2 is being called!"); + this.receiver.action(); + } + } + + export class Invoker { + private commands: Command[]; + + constructor() { + this.commands = []; + } + + public storeAndExecute(cmd: Command) { + this.commands.push(cmd); + cmd.execute(); + } + } + + export class Receiver { + public action(): void { + console.log("action is being called!"); + } + } +} + +(function main() { + var receiver: CommandPattern.Receiver = new CommandPattern.Receiver(), + command1: CommandPattern.Command = new CommandPattern.ConcreteCommand1(receiver), + command2: CommandPattern.Command = new CommandPattern.ConcreteCommand2(receiver), + invoker : CommandPattern.Invoker = new CommandPattern.Invoker(); + + invoker.storeAndExecute(command1); + invoker.storeAndExecute(command2); + +}()); + diff --git a/command/demo.ts b/command/demo.ts new file mode 100644 index 0000000..39f569b --- /dev/null +++ b/command/demo.ts @@ -0,0 +1,17 @@ +/// +namespace CommandPattern { + export namespace Demo { + + export function show() : void { + var receiver: CommandPattern.Receiver = new CommandPattern.Receiver(), + command1: CommandPattern.Command = new CommandPattern.ConcreteCommand1(receiver), + command2: CommandPattern.Command = new CommandPattern.ConcreteCommand2(receiver), + invoker : CommandPattern.Invoker = new CommandPattern.Invoker(); + + invoker.storeAndExecute(command1); + invoker.storeAndExecute(command2); + + + } + } +} diff --git a/composite/composite.ts b/composite/composite.ts index b090089..a5dac6d 100644 --- a/composite/composite.ts +++ b/composite/composite.ts @@ -1,66 +1,45 @@ -namespace ComponentPattern { - - export interface Component { - operation(): void; - } - - export class Composite implements Component { - - private list: Component[]; - private s: String; - - constructor(s: String) { - this.list = []; - this.s = s; - } - - public operation(): void { - console.log("`operation of `", this.s) - for (var i = 0; i < this.list.length; i += 1) { - this.list[i].operation(); - } - } - - public add(c: Component): void { - this.list.push(c); - } - - public remove(i: number): void { - if (this.list.length <= i) { - throw new Error("index out of bound!"); - } - this.list.splice(i, 1); - } - } - - export class Leaf implements Component { - private s: String; - constructor(s: String) { - this.s = s; - } - public operation(): void { - console.log("`operation` of Leaf", this.s, " is called."); - } - } -} - -(function main() { - var leaf1 = new ComponentPattern.Leaf("1"), - leaf2 = new ComponentPattern.Leaf("2"), - leaf3 = new ComponentPattern.Leaf("3"), - - composite1 = new ComponentPattern.Composite("Comp1"), - composite2 = new ComponentPattern.Composite("Comp2"); - - composite1.add(leaf1); - composite1.add(leaf2); - composite1.add(leaf3); - - composite1.remove(2); - - composite2.add(leaf1); - composite2.add(leaf3); - - composite1.operation(); - composite2.operation(); -}()); +namespace CompositePattern { + export interface Component { + operation(): void; + } + + export class Composite implements Component { + + private list: Component[]; + private s: String; + + constructor(s: String) { + this.list = []; + this.s = s; + } + + public operation(): void { + console.log("`operation of `", this.s) + for (var i = 0; i < this.list.length; i += 1) { + this.list[i].operation(); + } + } + + public add(c: Component): void { + this.list.push(c); + } + + public remove(i: number): void { + if (this.list.length <= i) { + throw new Error("index out of bound!"); + } + this.list.splice(i, 1); + } + } + + export class Leaf implements Component { + private s: String; + constructor(s: String) { + this.s = s; + } + public operation(): void { + console.log("`operation` of Leaf", this.s, " is called."); + } + } +} + diff --git a/composite/demo.ts b/composite/demo.ts new file mode 100644 index 0000000..993a124 --- /dev/null +++ b/composite/demo.ts @@ -0,0 +1,25 @@ +/// +namespace CompositePattern { + export namespace Demo { + export function show() : void { + var leaf1 = new CompositePattern.Leaf("1"), + leaf2 = new CompositePattern.Leaf("2"), + leaf3 = new CompositePattern.Leaf("3"), + + composite1 = new CompositePattern.Composite("Comp1"), + composite2 = new CompositePattern.Composite("Comp2"); + + composite1.add(leaf1); + composite1.add(leaf2); + composite1.add(leaf3); + + composite1.remove(2); + + composite2.add(leaf1); + composite2.add(leaf3); + + composite1.operation(); + composite2.operation(); + } + } +} diff --git a/decorator/decorator.ts b/decorator/decorator.ts index f3619db..2bf8e9b 100644 --- a/decorator/decorator.ts +++ b/decorator/decorator.ts @@ -1,54 +1,48 @@ -namespace DecoratorPattern { - - export interface Component { - operation(): void; - } - - export class ConcreteComponent implements Component { - private s: String; - - constructor(s: String) { - this.s = s; - } - - public operation(): void { - console.log("`operation` of ConcreteComponent", this.s, " is being called!"); - } - } - - export class Decorator implements Component { - private component: Component; - private id: Number; - - constructor(id: Number, component: Component) { - this.id = id; - this.component = component; - } - - public get Id(): Number { - return this.id; - } - - public operation(): void { - console.log("`operation` of Decorator", this.id, " is being called!"); - this.component.operation(); - } - } - - export class ConcreteDecorator extends Decorator { - constructor(id: Number, component: Component) { - super(id, component); - } - - public operation(): void { - super.operation(); - console.log("`operation` of ConcreteDecorator", this.Id, " is being called!"); - } - } -} - -(function main() { - var decorator1: DecoratorPattern.Decorator = new DecoratorPattern.ConcreteDecorator(1, new DecoratorPattern.ConcreteComponent("Comp1")); - - decorator1.operation(); -}()); \ No newline at end of file +namespace DecoratorPattern { + + export interface Component { + operation(): void; + } + + export class ConcreteComponent implements Component { + private s: String; + + constructor(s: String) { + this.s = s; + } + + public operation(): void { + console.log("`operation` of ConcreteComponent", this.s, " is being called!"); + } + } + + export class Decorator implements Component { + private component: Component; + private id: Number; + + constructor(id: Number, component: Component) { + this.id = id; + this.component = component; + } + + public get Id(): Number { + return this.id; + } + + public operation(): void { + console.log("`operation` of Decorator", this.id, " is being called!"); + this.component.operation(); + } + } + + export class ConcreteDecorator extends Decorator { + constructor(id: Number, component: Component) { + super(id, component); + } + + public operation(): void { + super.operation(); + console.log("`operation` of ConcreteDecorator", this.Id, " is being called!"); + } + } +} diff --git a/decorator/demo.ts b/decorator/demo.ts new file mode 100644 index 0000000..0a11b63 --- /dev/null +++ b/decorator/demo.ts @@ -0,0 +1,12 @@ +/// +namespace DecoratorPattern { + export namespace Demo { + + export function show() : void { + var decorator1: DecoratorPattern.Decorator = new DecoratorPattern.ConcreteDecorator(1, new DecoratorPattern.ConcreteComponent("Comp1")); + + decorator1.operation(); + } + } +} + diff --git a/facade/demo.ts b/facade/demo.ts new file mode 100644 index 0000000..66e82b4 --- /dev/null +++ b/facade/demo.ts @@ -0,0 +1,13 @@ +/// +namespace FacadePattern { + export namespace Demo { + export function show() : void { + var facade: FacadePattern.Facade = new FacadePattern.Facade(); + + facade.operation1(); + + facade.operation2(); + } + } +} + diff --git a/facade/facade.ts b/facade/facade.ts index fc59b63..6871b06 100644 --- a/facade/facade.ts +++ b/facade/facade.ts @@ -1,49 +1,40 @@ -namespace FacadePattern { - - export class Part1 { - public method1(): void { - console.log("`method1` of Part1"); - } - } - - export class Part2 { - public method2(): void { - console.log("`method2` of Part2"); - } - } - - export class Part3 { - public method3(): void { - console.log("`method3` of Part3"); - } - } - - export class Facade { - private part1: Part1 = new Part1(); - private part2: Part2 = new Part2(); - private part3: Part3 = new Part3(); - - public operation1(): void { - console.log("`operation1` is called ==="); - this.part1.method1(); - this.part2.method2(); - console.log("=========================="); - } - - public operation2(): void { - console.log("`operation2` is called ==="); - this.part1.method1(); - this.part3.method3(); - console.log("=========================="); - } - } -} - -(function main() { - var facade: FacadePattern.Facade = new FacadePattern.Facade(); - - facade.operation1(); - - facade.operation2(); - -}()); \ No newline at end of file +namespace FacadePattern { + + export class Part1 { + public method1(): void { + console.log("`method1` of Part1"); + } + } + + export class Part2 { + public method2(): void { + console.log("`method2` of Part2"); + } + } + + export class Part3 { + public method3(): void { + console.log("`method3` of Part3"); + } + } + + export class Facade { + private part1: Part1 = new Part1(); + private part2: Part2 = new Part2(); + private part3: Part3 = new Part3(); + + public operation1(): void { + console.log("`operation1` is called ==="); + this.part1.method1(); + this.part2.method2(); + console.log("=========================="); + } + + public operation2(): void { + console.log("`operation2` is called ==="); + this.part1.method1(); + this.part3.method3(); + console.log("=========================="); + } + } +} diff --git a/factory_method/demo.ts b/factory_method/demo.ts index d79f1ba..6f709af 100644 --- a/factory_method/demo.ts +++ b/factory_method/demo.ts @@ -12,4 +12,3 @@ namespace FactoryMethodPattern { } } -FactoryMethodPattern.Demo.show(); diff --git a/flyweight/demo.ts b/flyweight/demo.ts new file mode 100644 index 0000000..8a16701 --- /dev/null +++ b/flyweight/demo.ts @@ -0,0 +1,15 @@ +/// +namespace FlyweightPattern { + export namespace Demo { + export function show() : void { + var factory: FlyweightPattern.FlyweightFactory = new FlyweightPattern.FlyweightFactory(), + + conc1: FlyweightPattern.ConcreteFlyweight = factory.getFlyweight("conc1"), + conc2: FlyweightPattern.ConcreteFlyweight = factory.getFlyweight("conc2"); + + conc1.operation("1"); + conc2.operation("2"); + } + } +} + diff --git a/flyweight/flyweight.ts b/flyweight/flyweight.ts index 2903c87..548595c 100644 --- a/flyweight/flyweight.ts +++ b/flyweight/flyweight.ts @@ -1,54 +1,45 @@ -namespace FlyweightPattern { - - export interface Flyweight { - operation(s: String): void; - } - - export class ConcreteFlyweight implements Flyweight { - private instrinsicState: String; - - constructor(instrinsicState: String) { - this.instrinsicState = instrinsicState; - } - - public operation(s: String): void { - console.log("`operation` of ConcreteFlyweight", s, " is being called!"); - } - } - - export class UnsharedConcreteFlyweight implements Flyweight { - private allState: number; - - constructor(allState: number) { - this.allState = allState; - } - - public operation(s: String): void { - console.log("`operation` of UnsharedConcreteFlyweight", s, " is being called!"); - } - } - - export class FlyweightFactory { - - private fliesMap: { [s: string]: Flyweight; } = {}; - - constructor() { } - - public getFlyweight(key: string): Flyweight { - - if (this.fliesMap[key] === undefined || null) { - this.fliesMap[key] = new ConcreteFlyweight(key); - } - return this.fliesMap[key]; - } - } -} - -(function main() { - var factory: FlyweightPattern.FlyweightFactory = new FlyweightPattern.FlyweightFactory(), - conc1: FlyweightPattern.ConcreteFlyweight = factory.getFlyweight("conc1"), - conc2: FlyweightPattern.ConcreteFlyweight = factory.getFlyweight("conc2"); - - conc1.operation("1"); - conc2.operation("2"); -}()); \ No newline at end of file +namespace FlyweightPattern { + + export interface Flyweight { + operation(s: String): void; + } + + export class ConcreteFlyweight implements Flyweight { + private instrinsicState: String; + + constructor(instrinsicState: String) { + this.instrinsicState = instrinsicState; + } + + public operation(s: String): void { + console.log("`operation` of ConcreteFlyweight", s, " is being called!"); + } + } + + export class UnsharedConcreteFlyweight implements Flyweight { + private allState: number; + + constructor(allState: number) { + this.allState = allState; + } + + public operation(s: String): void { + console.log("`operation` of UnsharedConcreteFlyweight", s, " is being called!"); + } + } + + export class FlyweightFactory { + + private fliesMap: { [s: string]: Flyweight; } = {}; + + constructor() { } + + public getFlyweight(key: string): Flyweight { + + if (this.fliesMap[key] === undefined || null) { + this.fliesMap[key] = new ConcreteFlyweight(key); + } + return this.fliesMap[key]; + } + } +} diff --git a/interpreter/demo.ts b/interpreter/demo.ts new file mode 100644 index 0000000..34c08a0 --- /dev/null +++ b/interpreter/demo.ts @@ -0,0 +1,27 @@ +/// +namespace InterpreterPattern { + export namespace Demo { + + export function show() : void { + var context: InterpreterPattern.Context = new InterpreterPattern.Context(), + list = [], + i = 0, + max; + + list.push(new InterpreterPattern.NonterminalExpression()); + list.push(new InterpreterPattern.NonterminalExpression()); + list.push(new InterpreterPattern.NonterminalExpression()); + list.push(new InterpreterPattern.TerminalExpression()); + list.push(new InterpreterPattern.NonterminalExpression()); + list.push(new InterpreterPattern.NonterminalExpression()); + list.push(new InterpreterPattern.TerminalExpression()); + list.push(new InterpreterPattern.TerminalExpression()); + + for (i = 0, max = list.length; i < max; i += 1) { + list[i].interpret(context); + } + + + } + } +} diff --git a/interpreter/interpreter.ts b/interpreter/interpreter.ts index 434b510..50f66bd 100644 --- a/interpreter/interpreter.ts +++ b/interpreter/interpreter.ts @@ -1,40 +1,21 @@ -namespace InterPreterPattern { - export class Context { - } - - export interface AbstractExpression { - interpret(context: Context): void; - } - - export class TerminalExpression implements AbstractExpression { - public interpret(context: Context): void { - console.log("`interpret` method of TerminalExpression is being called!"); - } - } - - export class NonterminalExpression implements AbstractExpression { - - public interpret(context: Context): void { - console.log("`interpret` method of NonterminalExpression is being called!"); - } - } -} -(function main() { - var context: InterPreterPattern.Context = new InterPreterPattern.Context(), - list = [], - i = 0, - max; - - list.push(new InterPreterPattern.NonterminalExpression()); - list.push(new InterPreterPattern.NonterminalExpression()); - list.push(new InterPreterPattern.NonterminalExpression()); - list.push(new InterPreterPattern.TerminalExpression()); - list.push(new InterPreterPattern.NonterminalExpression()); - list.push(new InterPreterPattern.NonterminalExpression()); - list.push(new InterPreterPattern.TerminalExpression()); - list.push(new InterPreterPattern.TerminalExpression()); - - for (i = 0, max = list.length; i < max; i += 1) { - list[i].interpret(context); - } -}()); \ No newline at end of file +namespace InterpreterPattern { + export class Context { + } + + export interface AbstractExpression { + interpret(context: Context): void; + } + + export class TerminalExpression implements AbstractExpression { + public interpret(context: Context): void { + console.log("`interpret` method of TerminalExpression is being called!"); + } + } + + export class NonterminalExpression implements AbstractExpression { + + public interpret(context: Context): void { + console.log("`interpret` method of NonterminalExpression is being called!"); + } + } +} \ No newline at end of file diff --git a/iterator/demo.ts b/iterator/demo.ts new file mode 100644 index 0000000..7a96ebb --- /dev/null +++ b/iterator/demo.ts @@ -0,0 +1,16 @@ +/// +namespace IteratorPattern { + export namespace Demo { + + export function show() : void { + var nArray = [1, 7, 21, 657, 3, 2, 765, 13, 65], + numbers: IteratorPattern.Numbers = new IteratorPattern.Numbers(nArray), + it: IteratorPattern.ConcreteIterator = numbers.createIterator(); + + while (it.hasNext()) { + console.log(it.next()); + } + + } + } +} diff --git a/iterator/iterator.ts b/iterator/iterator.ts index 02d7a99..9f2bb3e 100644 --- a/iterator/iterator.ts +++ b/iterator/iterator.ts @@ -1,56 +1,47 @@ -namespace IteratorPattern { - export interface Iterator { - - next(): any; - hasNext(): boolean; - } - - export interface Aggregator { - createIterator(): Iterator; - } - - export class ConcreteIterator implements Iterator { - private collection: any[] = []; - private position: number = 0; - - constructor(collection: any[]) { - this.collection = collection; - } - - public next(): any { - // Error handling is left out - var result = this.collection[this.position]; - this.position += 1; - return result; - } - - public hasNext(): boolean { - if (this.position < this.collection.length) { - return true; - } else { - return false; - } - } - } - - export class Numbers implements Aggregator { - private collection: number[] = []; - - constructor(collection: number[]) { - this.collection = collection; - } - public createIterator(): Iterator { - return new ConcreteIterator(this.collection); - } - } -} - -(function main() { - var nArray = [1, 7, 21, 657, 3, 2, 765, 13, 65], - numbers: IteratorPattern.Numbers = new IteratorPattern.Numbers(nArray), - it: IteratorPattern.ConcreteIterator = numbers.createIterator(); - - while (it.hasNext()) { - console.log(it.next()); - } -}()); +namespace IteratorPattern { + export interface Iterator { + + next(): any; + hasNext(): boolean; + } + + export interface Aggregator { + createIterator(): Iterator; + } + + export class ConcreteIterator implements Iterator { + private collection: any[] = []; + private position: number = 0; + + constructor(collection: any[]) { + this.collection = collection; + } + + public next(): any { + // Error handling is left out + var result = this.collection[this.position]; + this.position += 1; + return result; + } + + public hasNext(): boolean { + if (this.position < this.collection.length) { + return true; + } else { + return false; + } + } + } + + export class Numbers implements Aggregator { + private collection: number[] = []; + + constructor(collection: number[]) { + this.collection = collection; + } + public createIterator(): Iterator { + return new ConcreteIterator(this.collection); + } + } +} + diff --git a/main.ts b/main.ts new file mode 100644 index 0000000..4a2d12c --- /dev/null +++ b/main.ts @@ -0,0 +1,113 @@ +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +// +// +// +declare var require : (moduleId : string) => any; +declare var process : any; + +var readline = require('readline'); + +namespace Patterns { + + + function printMenu() : void { + var menu = "= Creational Patterns == \n" + + " 1: Singleton \n" + + " 2: Abstract factory \n" + + " 3: Factory method \n" + + " 4: Builder \n" + + " 5: Prototype \n\n" + + "= Structural Patterns == \n" + + " 6: Adapter \n" + + " 7: Bridge \n" + + " 8: Composite \n" + + " 9: Decorator \n" + + " 10: Facade \n" + + " 11: Flyweight \n" + + " 12: Proxy \n\n" + + "= Behavioral Patterns == \n" + + " 13: Chain of responsibility \n" + + " 14: Command \n" + + " 15: Interpreter \n" + + " 16: Iterator \n" + + " 17: Mediator \n" + + " 18: Memento \n" + + " 19: Observer \n" + + " 20: State \n" + + " 21: Strategy \n" + + " 22: Template method \n" + + " 23: Visitor \n"; + + + console.log("\n\n"); + console.log("==== Choose one pattern to demonstrate ===="); + console.log("\n"); + console.log(menu); + } + + export function menu() : void { + var rl = readline.createInterface({ + input: process.stdin, + output: process.stdout + }); + + printMenu(); + rl.question("Which pattern would you like to check? ", function(answer) { + switch(+answer) { + case 1 : show(SingletonPattern); break; + case 2 : show(AbstractFactoryPattern); break; + case 3 : show(FactoryMethodPattern); break; + case 4 : show(BuilderPattern); break; + case 5 : show(PrototypePattern); break; + case 6 : show(AdapterPattern); break; + case 7 : show(BridgePattern); break; + case 8 : show(CompositePattern); break; + case 9 : show(DecoratorPattern); break; + case 10 : show(FacadePattern); break; + case 11 : show(FlyweightPattern); break; + case 12 : show(ProxyPattern); break; + case 13 : show(ChainOfResponsibilityPattern); break; + case 14 : show(CommandPattern); break; + case 15 : show(InterpreterPattern); break; + case 16 : show(IteratorPattern); break; + case 17 : show(MediatorPattern); break; + case 18 : show(MementoPattern); break; + case 19 : show(ObserverPattern); break; + case 20 : show(StatePattern); break; + case 21 : show(StrategyPattern); break; + case 22 : show(TemplateMethodPattern); break; + case 23 : show(VisitorPattern); break; + default : break; + } + rl.close(); + }); + } + + function show(Pattern : any) : void { + Pattern.Demo.show(); + } +} + +Patterns.menu(); diff --git a/mediator/demo.ts b/mediator/demo.ts new file mode 100644 index 0000000..01eac50 --- /dev/null +++ b/mediator/demo.ts @@ -0,0 +1,18 @@ +/// +namespace MediatorPattern { + export namespace Demo { + + export function show() : void { + var cm: MediatorPattern.ConcreteMediator = new MediatorPattern.ConcreteMediator(), + c1: MediatorPattern.ConcreteColleagueA = new MediatorPattern.ConcreteColleagueA(cm), + c2: MediatorPattern.ConcreteColleagueB = new MediatorPattern.ConcreteColleagueB(cm); + + cm.concreteColleagueA = c1; + cm.concreteColleagueB = c2; + + c1.send("`send` of ConcreteColleagueA is being called!"); + c2.send("`send` of ConcreteColleagueB is being called!"); + + } + } +} diff --git a/mediator/mediator.ts b/mediator/mediator.ts index 25f466b..601c5cf 100644 --- a/mediator/mediator.ts +++ b/mediator/mediator.ts @@ -1,75 +1,62 @@ -namespace MediatorPattern { - export interface Mediator { - send(msg: string, colleague: Colleague): void; - } - - export class Colleague { - public mediator: Mediator; - - constructor(mediator: Mediator) { - this.mediator = mediator; - } - - public send(msg: string): void { - throw new Error("Abstract Method!"); - } - - public receive(msg: string): void { - throw new Error("Abstract Method!"); - } - } - - export class ConcreteColleagueA extends Colleague { - constructor(mediator: Mediator) { - super(mediator); - } - - public send(msg: string): void { - this.mediator.send(msg, this); - } - - public receive(msg: string): void { - console.log(msg, "`receive` of ConcreteColleagueA is being called!"); - } - } - - export class ConcreteColleagueB extends Colleague { - constructor(mediator: Mediator) { - super(mediator); - } - - public send(msg: string): void { - this.mediator.send(msg, this); - } - - public receive(msg: string): void { - console.log(msg, "`receive` of ConcreteColleagueB is being called!"); - } - } - - export class ConcreteMediator implements Mediator { - public concreteColleagueA: ConcreteColleagueA; - public concreteColleagueB: ConcreteColleagueB; - - public send(msg: string, colleague: Colleague): void { - if (this.concreteColleagueA === colleague) { - this.concreteColleagueB.receive(msg); - } else { - this.concreteColleagueA.receive(msg); - } - } - } -} - -(function main() { - var cm: MediatorPattern.ConcreteMediator = new MediatorPattern.ConcreteMediator(), - c1: MediatorPattern.ConcreteColleagueA = new MediatorPattern.ConcreteColleagueA(cm), - c2: MediatorPattern.ConcreteColleagueB = new MediatorPattern.ConcreteColleagueB(cm); - - cm.concreteColleagueA = c1; - cm.concreteColleagueB = c2; - - c1.send("`send` of ConcreteColleagueA is being called!"); - c2.send("`send` of ConcreteColleagueB is being called!"); - -}()); \ No newline at end of file +namespace MediatorPattern { + export interface Mediator { + send(msg: string, colleague: Colleague): void; + } + + export class Colleague { + public mediator: Mediator; + + constructor(mediator: Mediator) { + this.mediator = mediator; + } + + public send(msg: string): void { + throw new Error("Abstract Method!"); + } + + public receive(msg: string): void { + throw new Error("Abstract Method!"); + } + } + + export class ConcreteColleagueA extends Colleague { + constructor(mediator: Mediator) { + super(mediator); + } + + public send(msg: string): void { + this.mediator.send(msg, this); + } + + public receive(msg: string): void { + console.log(msg, "`receive` of ConcreteColleagueA is being called!"); + } + } + + export class ConcreteColleagueB extends Colleague { + constructor(mediator: Mediator) { + super(mediator); + } + + public send(msg: string): void { + this.mediator.send(msg, this); + } + + public receive(msg: string): void { + console.log(msg, "`receive` of ConcreteColleagueB is being called!"); + } + } + + export class ConcreteMediator implements Mediator { + public concreteColleagueA: ConcreteColleagueA; + public concreteColleagueB: ConcreteColleagueB; + + public send(msg: string, colleague: Colleague): void { + if (this.concreteColleagueA === colleague) { + this.concreteColleagueB.receive(msg); + } else { + this.concreteColleagueA.receive(msg); + } + } + } +} diff --git a/memento/demo.ts b/memento/demo.ts new file mode 100644 index 0000000..ff0761e --- /dev/null +++ b/memento/demo.ts @@ -0,0 +1,16 @@ +/// +namespace MementoPattern { + export namespace Demo { + + export function show() : void { + var state: MementoPattern.State = new MementoPattern.State("... State "), + originator: MementoPattern.Originator = new MementoPattern.Originator(state), + careTaker: MementoPattern.CareTaker = new MementoPattern.CareTaker(); + + careTaker.Memento = originator.createMemento(); + originator.State = new MementoPattern.State("something else..."); + + originator.setMemento(careTaker.Memento); + } + } +} diff --git a/memento/memento.ts b/memento/memento.ts index 5f8d901..f0e6abd 100644 --- a/memento/memento.ts +++ b/memento/memento.ts @@ -1,80 +1,69 @@ -namespace MementoPattern { - export class State { - private str: string; - - constructor(str: string) { - this.str = str; - } - - get Str() : string { - return this.str; - } - - set Str(str: string) { - this.str = str; - } - } - - export class Originator { - private state: State; - - constructor(state: State) { - this.state = state; - } - - get State(): State { - return this.state; - } - - set State(state: State) { - console.log("State :: ", state); - this.state = state; - } - - public createMemento(): Memento { - console.log("creates a memento with a given state!"); - return new Memento(this.state); - } - - public setMemento(memento: Memento) { - console.log("sets the state back"); - this.State = memento.State; - } - } - - export class Memento { - private state: State; - - constructor (state: State) { - this.state = state; - } - - get State(): State { - console.log("get memento's state"); - return this.state; - } - } - - export class CareTaker { - private memento: Memento; - - get Memento(): Memento { - return this.memento; - } - - set Memento(memento: Memento) { - this.memento = memento; - } - } -} - -(function main() { - var state: MementoPattern.State = new MementoPattern.State("... State "), - originator: MementoPattern.Originator = new MementoPattern.Originator(state), - careTaker: MementoPattern.CareTaker = new MementoPattern.CareTaker(); - - careTaker.Memento = originator.createMemento(); - originator.State = new MementoPattern.State("something else..."); - - originator.setMemento(careTaker.Memento); -}()); \ No newline at end of file +namespace MementoPattern { + export class State { + private str: string; + + constructor(str: string) { + this.str = str; + } + + get Str() : string { + return this.str; + } + + set Str(str: string) { + this.str = str; + } + } + + export class Originator { + private state: State; + + constructor(state: State) { + this.state = state; + } + + get State(): State { + return this.state; + } + + set State(state: State) { + console.log("State :: ", state); + this.state = state; + } + + public createMemento(): Memento { + console.log("creates a memento with a given state!"); + return new Memento(this.state); + } + + public setMemento(memento: Memento) { + console.log("sets the state back"); + this.State = memento.State; + } + } + + export class Memento { + private state: State; + + constructor (state: State) { + this.state = state; + } + + get State(): State { + console.log("get memento's state"); + return this.state; + } + } + + export class CareTaker { + private memento: Memento; + + get Memento(): Memento { + return this.memento; + } + + set Memento(memento: Memento) { + this.memento = memento; + } + } +} diff --git a/observer/demo.ts b/observer/demo.ts new file mode 100644 index 0000000..9fd9635 --- /dev/null +++ b/observer/demo.ts @@ -0,0 +1,17 @@ +/// +namespace ObserverPattern { + export namespace Demo { + + export function show() : void { + var sub: ObserverPattern.ConcreteSubject = new ObserverPattern.ConcreteSubject(); + + sub.register(new ObserverPattern.ConcreteObserver(sub, "Jancsi")); + sub.register(new ObserverPattern.ConcreteObserver(sub, "Julcsa")); + sub.register(new ObserverPattern.ConcreteObserver(sub, "Marcsa")); + + sub.SubjectState = 123; + sub.notify(); + + } + } +} diff --git a/observer/observer.ts b/observer/observer.ts index 8e3bd8a..24f0d91 100644 --- a/observer/observer.ts +++ b/observer/observer.ts @@ -1,82 +1,71 @@ -namespace ObserverPattern { - export class Subject { - private observers: Observer[] = []; - - public register(observer: Observer): void { - console.log(observer, "is pushed!"); - this.observers.push(observer); - } - - public unregister(observer: Observer): void { - var n: number = this.observers.indexOf(observer); - console.log(observer, "is removed"); - this.observers.splice(n, 1); - } - - public notify(): void { - console.log("notify all the observers", this.observers); - var i: number - , max: number; - - for (i = 0, max = this.observers.length; i < max; i += 1) { - this.observers[i].notify(); - } - } - } - - export class ConcreteSubject extends Subject { - private subjectState: number; - - get SubjectState(): number { - return this.subjectState; - } - - set SubjectState(subjectState: number) { - this.subjectState = subjectState; - } - } - - export class Observer { - public notify(): void { - throw new Error("Abstract Method!"); - } - } - - export class ConcreteObserver extends Observer { - private name: string; - private state: number; - private subject: ConcreteSubject; - - constructor (subject: ConcreteSubject, name: string) { - super(); - console.log("ConcreteObserver", name, "is created!"); - this.subject = subject; - this.name = name; - } - - public notify(): void { - console.log("ConcreteObserver's notify method"); - console.log(this.name, this.state); - this.state = this.subject.SubjectState; - } - - get Subject(): ConcreteSubject { - return this.subject; - } - - set Subject(subject: ConcreteSubject) { - this.subject = subject; - } - } -} - -(function main() { - var sub: ObserverPattern.ConcreteSubject = new ObserverPattern.ConcreteSubject(); - - sub.register(new ObserverPattern.ConcreteObserver(sub, "Jancsi")); - sub.register(new ObserverPattern.ConcreteObserver(sub, "Julcsa")); - sub.register(new ObserverPattern.ConcreteObserver(sub, "Marcsa")); - - sub.SubjectState = 123; - sub.notify(); -}()); \ No newline at end of file +namespace ObserverPattern { + export class Subject { + private observers: Observer[] = []; + + public register(observer: Observer): void { + console.log(observer, "is pushed!"); + this.observers.push(observer); + } + + public unregister(observer: Observer): void { + var n: number = this.observers.indexOf(observer); + console.log(observer, "is removed"); + this.observers.splice(n, 1); + } + + public notify(): void { + console.log("notify all the observers", this.observers); + var i: number + , max: number; + + for (i = 0, max = this.observers.length; i < max; i += 1) { + this.observers[i].notify(); + } + } + } + + export class ConcreteSubject extends Subject { + private subjectState: number; + + get SubjectState(): number { + return this.subjectState; + } + + set SubjectState(subjectState: number) { + this.subjectState = subjectState; + } + } + + export class Observer { + public notify(): void { + throw new Error("Abstract Method!"); + } + } + + export class ConcreteObserver extends Observer { + private name: string; + private state: number; + private subject: ConcreteSubject; + + constructor (subject: ConcreteSubject, name: string) { + super(); + console.log("ConcreteObserver", name, "is created!"); + this.subject = subject; + this.name = name; + } + + public notify(): void { + console.log("ConcreteObserver's notify method"); + console.log(this.name, this.state); + this.state = this.subject.SubjectState; + } + + get Subject(): ConcreteSubject { + return this.subject; + } + + set Subject(subject: ConcreteSubject) { + this.subject = subject; + } + } +} diff --git a/proxy/demo.ts b/proxy/demo.ts new file mode 100644 index 0000000..cab5aa3 --- /dev/null +++ b/proxy/demo.ts @@ -0,0 +1,18 @@ +/// +namespace ProxyPattern { + export namespace Demo { + export function show() : void { + var proxy1: ProxyPattern.Proxy = new ProxyPattern.Proxy("proxy1"), + + proxy2: ProxyPattern.Proxy = new ProxyPattern.Proxy("proxy2"); + + proxy1.doAction(); + proxy1.doAction(); + proxy2.doAction(); + proxy2.doAction(); + proxy1.doAction(); + + } + } +} + diff --git a/proxy/proxy.ts b/proxy/proxy.ts index b9ae846..ddd7209 100644 --- a/proxy/proxy.ts +++ b/proxy/proxy.ts @@ -1,45 +1,34 @@ -namespace ProxyPattern { - export interface Subject { - doAction(): void; - } - - export class Proxy implements Subject { - private realSubject: RealSubject; - private s: string; - - constructor(s: string) { - this.s = s; - } - - public doAction(): void { - console.log("`doAction` of Proxy(", this.s, ")"); - if (this.realSubject === null || this.realSubject === undefined) { - console.log("creating a new RealSubject."); - this.realSubject = new RealSubject(this.s); - } - this.realSubject.doAction(); - } - } - - export class RealSubject implements Subject { - private s: string; - - constructor(s: string) { - this.s = s; - } - public doAction(): void { - console.log("`doAction` of RealSubject", this.s, "is being called!"); - } - } -} - -(function main() { - var proxy1: ProxyPattern.Proxy = new ProxyPattern.Proxy("proxy1"), - proxy2: ProxyPattern.Proxy = new ProxyPattern.Proxy("proxy2"); - - proxy1.doAction(); - proxy1.doAction(); - proxy2.doAction(); - proxy2.doAction(); - proxy1.doAction(); -}()); \ No newline at end of file +namespace ProxyPattern { + export interface Subject { + doAction(): void; + } + + export class Proxy implements Subject { + private realSubject: RealSubject; + private s: string; + + constructor(s: string) { + this.s = s; + } + + public doAction(): void { + console.log("`doAction` of Proxy(", this.s, ")"); + if (this.realSubject === null || this.realSubject === undefined) { + console.log("creating a new RealSubject."); + this.realSubject = new RealSubject(this.s); + } + this.realSubject.doAction(); + } + } + + export class RealSubject implements Subject { + private s: string; + + constructor(s: string) { + this.s = s; + } + public doAction(): void { + console.log("`doAction` of RealSubject", this.s, "is being called!"); + } + } +} diff --git a/singleton/spec/singleton.spec.js b/singleton/spec/singleton.spec.js deleted file mode 100644 index 9b88c4c..0000000 --- a/singleton/spec/singleton.spec.js +++ /dev/null @@ -1,25 +0,0 @@ -define("singleton", function () { - var singleton1, - singleton2; - - beforeEach(function () { - singleton1 = SingletonPattern.Singleton.Instance; - }); - - describe("when is initialized", function () { - it("should not be undefined", function () { - expect(singleton1).not.toBeUndefined(); - }); - - it("should not be null", function () { - expect(singleton1).not.toBeNull(); - }); - }); - - describe("when two instances are initialized", function () { - it("should be equal", function () { - singleton2 = Singleton.Instance; - expect(singleton1).toBe(singleton2); - }); - }); -}); \ No newline at end of file diff --git a/singleton/src/demo.ts b/singleton/src/demo.ts index 375b53c..35a972f 100644 --- a/singleton/src/demo.ts +++ b/singleton/src/demo.ts @@ -15,4 +15,3 @@ namespace SingletonPattern { } } -SingletonPattern.Demo.show(); diff --git a/state/demo.ts b/state/demo.ts new file mode 100644 index 0000000..49da3b4 --- /dev/null +++ b/state/demo.ts @@ -0,0 +1,18 @@ +/// +namespace StatePattern { + export namespace Demo { + + export function show() : void { + var context: StatePattern.Context = new StatePattern.Context(new StatePattern.ConcreteStateA()); + context.request(); + context.request(); + context.request(); + context.request(); + context.request(); + context.request(); + context.request(); + context.request(); + + } + } +} diff --git a/state/state.ts b/state/state.ts index 089ab99..705b7a2 100644 --- a/state/state.ts +++ b/state/state.ts @@ -1,54 +1,41 @@ -namespace StatePattern { - export interface State { - handle(context: Context): void; - } - - export class ConcreteStateA implements State { - public handle(context: Context): void { - console.log("`handle` method of ConcreteStateA is being called!"); - context.State = new ConcreteStateB(); - } - } - - export class ConcreteStateB implements State { - public handle(context: Context): void { - console.log("`handle` method of ConcreteStateB is being called!"); - context.State = new ConcreteStateA(); - } - } - - export class Context { - private state: State; - - constructor(state: State) { - this.state = state; - } - - get State(): State { - return this.state; - } - - set State(state: State) { - this.state = state; - } - - public request(): void { - console.log("request is being called!"); - this.state.handle(this); - } - } -} - - -(function main() { - var context: StatePattern.Context = new StatePattern.Context(new StatePattern.ConcreteStateA()); - context.request(); - context.request(); - context.request(); - context.request(); - context.request(); - context.request(); - context.request(); - context.request(); - -}()); \ No newline at end of file +namespace StatePattern { + export interface State { + handle(context: Context): void; + } + + export class ConcreteStateA implements State { + public handle(context: Context): void { + console.log("`handle` method of ConcreteStateA is being called!"); + context.State = new ConcreteStateB(); + } + } + + export class ConcreteStateB implements State { + public handle(context: Context): void { + console.log("`handle` method of ConcreteStateB is being called!"); + context.State = new ConcreteStateA(); + } + } + + export class Context { + private state: State; + + constructor(state: State) { + this.state = state; + } + + get State(): State { + return this.state; + } + + set State(state: State) { + this.state = state; + } + + public request(): void { + console.log("request is being called!"); + this.state.handle(this); + } + } +} + diff --git a/strategy/demo.ts b/strategy/demo.ts new file mode 100644 index 0000000..687cb18 --- /dev/null +++ b/strategy/demo.ts @@ -0,0 +1,19 @@ +/// +namespace StrategyPattern { + export namespace Demo { + + export function show() : void { + var context: StrategyPattern.Context = new StrategyPattern.Context(new StrategyPattern.ConcreteStrategy1()); + + context.executeStrategy(); + + context = new StrategyPattern.Context(new StrategyPattern.ConcreteStrategy2()); + context.executeStrategy(); + + context = new StrategyPattern.Context(new StrategyPattern.ConcreteStrategy3()); + context.executeStrategy(); + + + } + } +} diff --git a/strategy/strategy.ts b/strategy/strategy.ts index 86d5794..7aed97f 100644 --- a/strategy/strategy.ts +++ b/strategy/strategy.ts @@ -1,47 +1,36 @@ -namespace StrategyPattern { - export interface Strategy { - execute(): void; - } - - export class ConcreteStrategy1 implements Strategy { - public execute(): void { - console.log("`execute` method of ConcreteStrategy1 is being called"); - } - } - - export class ConcreteStrategy2 implements Strategy { - public execute(): void { - console.log("`execute` method of ConcreteStrategy2 is being called"); - } - } - - export class ConcreteStrategy3 implements Strategy { - public execute(): void { - console.log("`execute` method of ConcreteStrategy3 is being called"); - } - } - - export class Context { - private strategy: Strategy; - - constructor(strategy: Strategy) { - this.strategy = strategy; - } - - public executeStrategy(): void { - this.strategy.execute(); - } - } -} - -(function main() { - var context: StrategyPattern.Context = new StrategyPattern.Context(new StrategyPattern.ConcreteStrategy1()); - context.executeStrategy(); - - context = new StrategyPattern.Context(new StrategyPattern.ConcreteStrategy2()); - context.executeStrategy(); - - context = new StrategyPattern.Context(new StrategyPattern.ConcreteStrategy3()); - context.executeStrategy(); - -}()); +namespace StrategyPattern { + export interface Strategy { + execute(): void; + } + + export class ConcreteStrategy1 implements Strategy { + public execute(): void { + console.log("`execute` method of ConcreteStrategy1 is being called"); + } + } + + export class ConcreteStrategy2 implements Strategy { + public execute(): void { + console.log("`execute` method of ConcreteStrategy2 is being called"); + } + } + + export class ConcreteStrategy3 implements Strategy { + public execute(): void { + console.log("`execute` method of ConcreteStrategy3 is being called"); + } + } + + export class Context { + private strategy: Strategy; + + constructor(strategy: Strategy) { + this.strategy = strategy; + } + + public executeStrategy(): void { + this.strategy.execute(); + } + } +} + diff --git a/template_method/demo.ts b/template_method/demo.ts new file mode 100644 index 0000000..52eda7f --- /dev/null +++ b/template_method/demo.ts @@ -0,0 +1,14 @@ +/// +namespace TemplateMethodPattern { + export namespace Demo { + + export function show() : void { + var c1: TemplateMethodPattern.ConcreteClass1 = new TemplateMethodPattern.ConcreteClass1(), + c2: TemplateMethodPattern.ConcreteClass2 = new TemplateMethodPattern.ConcreteClass2(); + + c1.templateMethod(); + c2.templateMethod(); + + } + } +} diff --git a/template_method/templateMethod.ts b/template_method/templateMethod.ts index 424d4ac..559a99a 100644 --- a/template_method/templateMethod.ts +++ b/template_method/templateMethod.ts @@ -1,58 +1,50 @@ -namespace TemplateMethodPattern { - export class AbstractClass { - public method1(): void { - throw new Error("Abstract Method"); - } - - public method2(): void { - throw new Error("Abstract Method"); - } - - public method3(): void { - throw new Error("Abstract Method"); - } - - public templateMethod(): void { - console.log("templateMethod is being called"); - this.method1(); - this.method2(); - this.method3(); - } - } - - export class ConcreteClass1 extends AbstractClass { - public method1(): void { - console.log("method1 of ConcreteClass1"); - } - - public method2(): void { - console.log("method2 of ConcreteClass1"); - } - - public method3(): void { - console.log("method3 of ConcreteClass1"); - } - } - - export class ConcreteClass2 extends AbstractClass { - public method1(): void { - console.log("method1 of ConcreteClass2"); - } - - public method2(): void { - console.log("method2 of ConcreteClass2"); - } - - public method3(): void { - console.log("method3 of ConcreteClass2"); - } - } -} - -(function main() { - var c1: TemplateMethodPattern.ConcreteClass1 = new TemplateMethodPattern.ConcreteClass1(), - c2: TemplateMethodPattern.ConcreteClass2 = new TemplateMethodPattern.ConcreteClass2(); - - c1.templateMethod(); - c2.templateMethod(); -}()); \ No newline at end of file +namespace TemplateMethodPattern { + export class AbstractClass { + public method1(): void { + throw new Error("Abstract Method"); + } + + public method2(): void { + throw new Error("Abstract Method"); + } + + public method3(): void { + throw new Error("Abstract Method"); + } + + public templateMethod(): void { + console.log("templateMethod is being called"); + this.method1(); + this.method2(); + this.method3(); + } + } + + export class ConcreteClass1 extends AbstractClass { + public method1(): void { + console.log("method1 of ConcreteClass1"); + } + + public method2(): void { + console.log("method2 of ConcreteClass1"); + } + + public method3(): void { + console.log("method3 of ConcreteClass1"); + } + } + + export class ConcreteClass2 extends AbstractClass { + public method1(): void { + console.log("method1 of ConcreteClass2"); + } + + public method2(): void { + console.log("method2 of ConcreteClass2"); + } + + public method3(): void { + console.log("method3 of ConcreteClass2"); + } + } +} diff --git a/tsconfig.json b/tsconfig.json index 22b6982..be27949 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,33 +1,58 @@ { "compilerOptions": { - "module": "commonjs", + "module": "system", "target": "ES5", "noImplicitAny": false, - "sourceMap": false + "sourceMap": false, + "outFile": "patterns.js" }, "files": [ + "main.ts", "abstract_factory/abstractFactory.ts", + "abstract_factory/demo.ts", "adapter/adapter.ts", + "adapter/demo.ts", "bridge/bridge.ts", + "bridge/demo.ts", "builder/builder.ts", + "builder/demo.ts", "chain_of_responsibility/chainOfResponsibility.ts", + "chain_of_responsibility/demo.ts", "command/command.ts", + "command/demo.ts", "composite/composite.ts", + "composite/demo.ts", "decorator/decorator.ts", + "decorator/demo.ts", "facade/facade.ts", + "facade/demo.ts", "factory_method/factoryMethod.ts", + "factory_method/demo.ts", "flyweight/flyweight.ts", + "flyweight/demo.ts", "interpreter/interpreter.ts", + "interpreter/demo.ts", "mediator/mediator.ts", + "mediator/demo.ts", "iterator/iterator.ts", - "mediator/mediator.ts", + "iterator/demo.ts", "memento/memento.ts", + "memento/demo.ts", "observer/observer.ts", + "observer/demo.ts", "prototype/prototype.ts", + "prototype/demo.ts", "proxy/proxy.ts", + "proxy/demo.ts", "singleton/src/singleton.ts", + "singleton/src/demo.ts", "state/state.ts", + "state/demo.ts", "strategy/strategy.ts", - "template_method/templateMethod.ts" + "strategy/demo.ts", + "template_method/templateMethod.ts", + "template_method/demo.ts", + "visitor/visitor.ts", + "visitor/demo.ts" ] } diff --git a/visitor/demo.ts b/visitor/demo.ts new file mode 100644 index 0000000..ab6d076 --- /dev/null +++ b/visitor/demo.ts @@ -0,0 +1,19 @@ +/// +namespace VisitorPattern { + export namespace Demo { + + export function show() : void { + var objs: VisitorPattern.Objs = new VisitorPattern.Objs(); + + objs.attach( new VisitorPattern.ConcreteElement1()); + objs.attach( new VisitorPattern.ConcreteElement2()); + + var v1: VisitorPattern.ConcreteVisitor1 = new VisitorPattern.ConcreteVisitor1(), + v2: VisitorPattern.ConcreteVisitor2 = new VisitorPattern.ConcreteVisitor2(); + + objs.operate(v1); + objs.operate(v2); + + } + } +} diff --git a/visitor/visitor.ts b/visitor/visitor.ts index b88c9bb..25361cc 100644 --- a/visitor/visitor.ts +++ b/visitor/visitor.ts @@ -1,82 +1,69 @@ -namespace VisitorPattern { - export interface Visitor { - visitConcreteElement1(concreteElement1: ConcreteElement1): void; - visitConcreteElement2(concreteElement2: ConcreteElement2): void; - } - - export class ConcreteVisitor1 implements Visitor { - public visitConcreteElement1(concreteElement1: ConcreteElement1): void { - console.log("`visitConcreteElement1` of ConcreteVisitor1 is being called!"); - } - - public visitConcreteElement2(concreteElement2: ConcreteElement2): void { - console.log("`visitConcreteElement2` of ConcreteVisitor1 is being called!"); - } - } - - export class ConcreteVisitor2 implements Visitor { - public visitConcreteElement1(concreteElement1: ConcreteElement1): void { - console.log("`visitConcreteElement1` of ConcreteVisitor2 is being called!"); - } - - public visitConcreteElement2(concreteElement2: ConcreteElement2): void { - console.log("`visitConcreteElement2` of ConcreteVisitor2 is being called!"); - } - } - - - export interface Element { - operate(visitor: Visitor): void; - } - - export class ConcreteElement1 { - public operate(visitor: Visitor): void { - console.log("`operate` of ConcreteElement1 is being called!"); - visitor.visitConcreteElement1(this); - } - } - - export class ConcreteElement2 { - public operate(visitor: Visitor): void { - console.log("`operate` of ConcreteElement2 is being called!"); - visitor.visitConcreteElement2(this); - } - } - - export class Objs { - private elements: Element[] = []; - - public attach(e: Element): void { - this.elements.push(e); - } - - public detach(e: Element): void { - var index = this.elements.indexOf(e); - this.elements.splice(index, 1); - } - - public operate(visitor: Visitor): void { - var i = 0, - max = this.elements.length; - - for(; i < max; i += 1) { - this.elements[i].operate(visitor); - } - } - } - -} - - -(function main() { - var objs: VisitorPattern.Objs = new VisitorPattern.Objs(); - - objs.attach( new VisitorPattern.ConcreteElement1()); - objs.attach( new VisitorPattern.ConcreteElement2()); - - var v1: VisitorPattern.ConcreteVisitor1 = new VisitorPattern.ConcreteVisitor1(), - v2: VisitorPattern.ConcreteVisitor2 = new VisitorPattern.ConcreteVisitor2(); - - objs.operate(v1); - objs.operate(v2); -}()); \ No newline at end of file +namespace VisitorPattern { + export interface Visitor { + visitConcreteElement1(concreteElement1: ConcreteElement1): void; + visitConcreteElement2(concreteElement2: ConcreteElement2): void; + } + + export class ConcreteVisitor1 implements Visitor { + public visitConcreteElement1(concreteElement1: ConcreteElement1): void { + console.log("`visitConcreteElement1` of ConcreteVisitor1 is being called!"); + } + + public visitConcreteElement2(concreteElement2: ConcreteElement2): void { + console.log("`visitConcreteElement2` of ConcreteVisitor1 is being called!"); + } + } + + export class ConcreteVisitor2 implements Visitor { + public visitConcreteElement1(concreteElement1: ConcreteElement1): void { + console.log("`visitConcreteElement1` of ConcreteVisitor2 is being called!"); + } + + public visitConcreteElement2(concreteElement2: ConcreteElement2): void { + console.log("`visitConcreteElement2` of ConcreteVisitor2 is being called!"); + } + } + + + export interface Element { + operate(visitor: Visitor): void; + } + + export class ConcreteElement1 { + public operate(visitor: Visitor): void { + console.log("`operate` of ConcreteElement1 is being called!"); + visitor.visitConcreteElement1(this); + } + } + + export class ConcreteElement2 { + public operate(visitor: Visitor): void { + console.log("`operate` of ConcreteElement2 is being called!"); + visitor.visitConcreteElement2(this); + } + } + + export class Objs { + private elements: Element[] = []; + + public attach(e: Element): void { + this.elements.push(e); + } + + public detach(e: Element): void { + var index = this.elements.indexOf(e); + this.elements.splice(index, 1); + } + + public operate(visitor: Visitor): void { + var i = 0, + max = this.elements.length; + + for(; i < max; i += 1) { + this.elements[i].operate(visitor); + } + } + } + +} +