Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 86 additions & 0 deletions DesignPattern/18-模板方法模式.md
Original file line number Diff line number Diff line change
Expand Up @@ -618,3 +618,89 @@ func main() {
}
```

### Typescript

``` typescript
abstract class AbstractTemplate {
coffeeName: string;

constructor(coffee: string) {
this.coffeeName = coffee;
}
templateMethod() {
console.log(`Making ${this.coffeeName}:`);
this.grindingCoffeeBeans();
this.brewingCoffee();
this.addingCondiments();
console.log();
}

abstract grindingCoffeeBeans(): void;
abstract brewingCoffee(): void;
abstract addingCondiments(): void;
}

class AmericaCoffee extends AbstractTemplate {
constructor() {
super("American Coffee");
}

grindingCoffeeBeans(): void {
console.log("Grinding coffee beans");
}

brewingCoffee(): void {
console.log("Brewing coffee");
}

addingCondiments(): void {
console.log("Adding condiments");
}
}

class Latte extends AbstractTemplate {
constructor() {
super("Latte");
}

grindingCoffeeBeans(): void {
console.log("Grinding coffee beans");
}

brewingCoffee(): void {
console.log("Brewing coffee");
}

addingCondiments(): void {
console.log("Adding milk");
console.log("Adding condiments");
}
}

// @ts-ignore
entry(2, (...args) => {
args.forEach((type) => {
let coffee: AbstractTemplate;
if (type === 1) {
coffee = new AmericaCoffee();
} else if (type === 2) {
coffee = new Latte();
} else {
throw "type error";
}

coffee.templateMethod();
});
})(1)(2);

export function entry(count: number, fn: (...args: any) => void) {
function dfs(...args) {
if (args.length < count) {
return (arg) => dfs(...args, arg);
}

return fn(...args);
}
return dfs;
}
```