|
| 1 | +interface AbstractFactory { |
| 2 | + createProductA(): AbstractProductA; |
| 3 | + createProductB(): AbstractProductB; |
| 4 | +} |
| 5 | + |
| 6 | +class ConcreteFactory1 implements AbstractFactory { |
| 7 | + public createProductA(): AbstractProductA { |
| 8 | + return new ConcreteProductA1(); |
| 9 | + } |
| 10 | + public createProductB(): AbstractProductB { |
| 11 | + return new ConcreteProductB1(); |
| 12 | + } |
| 13 | +} |
| 14 | + |
| 15 | +class ConcreteFactory2 implements AbstractFactory { |
| 16 | + public createProductA(): AbstractProductA { |
| 17 | + return new ConcreteProductA2(); |
| 18 | + } |
| 19 | + public createProductB(): AbstractProductB { |
| 20 | + return new ConcreteProductB2(); |
| 21 | + } |
| 22 | +} |
| 23 | + |
| 24 | +interface AbstractProductA { |
| 25 | + usefulFunctionA(): string; |
| 26 | +} |
| 27 | + |
| 28 | +class ConcreteProductA1 implements AbstractProductA { |
| 29 | + public usefulFunctionA(): string { |
| 30 | + return 'The result of the product A1.'; |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +class ConcreteProductA2 implements AbstractProductA { |
| 35 | + public usefulFunctionA(): string { |
| 36 | + return 'The result of the product A2.'; |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +interface AbstractProductB { |
| 41 | + usefulFunctionB(): string; |
| 42 | + |
| 43 | + anotherUsefulFunctionB(callaborator: AbstractProductA): string; |
| 44 | +} |
| 45 | + |
| 46 | +class ConcreteProductB1 implements AbstractProductB { |
| 47 | + public usefulFunctionB(): string { |
| 48 | + return 'The result of the product B1.'; |
| 49 | + } |
| 50 | + |
| 51 | + public anotherUsefulFunctionB(collaborator: AbstractProductA): string { |
| 52 | + const result = collaborator.usefulFunctionA(); |
| 53 | + return `The result of the B1 collaborating with the (${result})`; |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +class ConcreteProductB2 implements AbstractProductB { |
| 58 | + public usefulFunctionB(): string { |
| 59 | + return 'The result of the product B2.'; |
| 60 | + } |
| 61 | + |
| 62 | + public anotherUsefulFunctionB(collaborator: AbstractProductA): string { |
| 63 | + const result = collaborator.usefulFunctionA(); |
| 64 | + return `The result of the B2 collaborating with the (${result})`; |
| 65 | + } |
| 66 | +} |
| 67 | + |
| 68 | +function clientCode(factory: AbstractFactory) { |
| 69 | + const productA = factory.createProductA(); |
| 70 | + const productB = factory.createProductB(); |
| 71 | + |
| 72 | + console.log(productB.usefulFunctionB()); |
| 73 | + console.log(productB.anotherUsefulFunctionB(productA)); |
| 74 | +} |
| 75 | + |
| 76 | +console.log('Client: Testing client code with the first factory type...'); |
| 77 | +clientCode(new ConcreteFactory1()); |
| 78 | + |
| 79 | +console.log(''); |
| 80 | + |
| 81 | +console.log('Client: Testing the same client code with the second factory type...'); |
| 82 | +clientCode(new ConcreteFactory2()); |
0 commit comments