diff --git a/chapters/chapter-4_Structural_Design_Patterns/Bridge.ts b/chapters/chapter-4_Structural_Design_Patterns/Bridge.ts new file mode 100644 index 0000000..60b97d0 --- /dev/null +++ b/chapters/chapter-4_Structural_Design_Patterns/Bridge.ts @@ -0,0 +1,91 @@ +interface Box { + id: string; + value: string; +} +interface BoxArranger { + arrangeItem(item: Box, items: Box[]): Box[]; +} + +abstract class BoxContainer { + constructor(public items: Box[] = [], protected boxArranger: BoxArranger) {} + arrangeItem(item: Box) {} +} + +class StraightBoxContainer extends BoxContainer { + arrangeItem(item: Box) { + this.items = this.boxArranger.arrangeItem(item, this.items); + } +} + +class ReversingBoxContainer extends BoxContainer { + arrangeItem(item: Box) { + this.items = this.boxArranger.arrangeItem(item, this.items).reverse(); + } +} + +class PutLastBoxArranger implements BoxArranger { + arrangeItem(item: Box, items: Box[]): Box[] { + items = items.concat(item); + return items; + } +} + +class PutFirstBoxArranger implements BoxArranger { + arrangeItem(item: Box, items: Box[]): Box[] { + let result = items.slice(); + result.unshift(item); + return result; + } +} +const items: Box[] = [ + { + id: "1", + value: "abc", + }, +]; +const pfa = new PutFirstBoxArranger(); +const pla = new PutLastBoxArranger(); +const rv = new StraightBoxContainer(items, pla); +rv.arrangeItem({ + id: "3", + value: "dfa", +}); // [ { id: '3', value: 'dfa' }, { id: '1', value: 'abc' } ] +console.log(rv.items); +const sc = new StraightBoxContainer(items, pfa); +sc.arrangeItem({ + id: "3", + value: "dfa", +}); +console.log(sc.items); +[ + { id: "3", value: "dfa" }, + { id: "1", value: "abc" }, +]; + +// // Implementor type +// interface StorageItem { +// id: string; +// value: string; +// } +// type ExtendedStorageItem = StorageItem & { +// createdAt: Date; +// }; +// // Abstraction type +// interface List { +// push(item: T); +// pop(): T; +// shift(): T; +// unshift(): T; +// } +// interface Node { +// value: number; +// next: Node; +// } +// class ArrayList implements List { +// constructor(private items: StorageItem) {} +// // implements methods of List +// } +// class LinkedList implements List { +// constructor(private root: Node, private items: StorageItem) {} +// // implements methods of List +// }