-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #88 from GuoXiCheng/dev-c
update docs
- Loading branch information
Showing
2 changed files
with
59 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
# 策略模式 | ||
|
||
::: playground#ts 策略模式交互演示 | ||
|
||
@file index.ts | ||
|
||
```ts | ||
interface TaxStrategy { | ||
caculateTax(amount: number): number; | ||
} | ||
|
||
class USATaxStrategy implements TaxStrategy { | ||
caculateTax(amount: number) { | ||
return amount * 0.2; | ||
} | ||
} | ||
|
||
class ChinaTaxStrategy implements TaxStrategy { | ||
caculateTax(amount: number) { | ||
return amount * 0.1; | ||
} | ||
} | ||
|
||
class TaxCalculate { | ||
private strategy: TaxStrategy; | ||
|
||
constructor(taxStrategy: TaxStrategy) { | ||
this.strategy = taxStrategy; | ||
} | ||
|
||
calculate(amount: number): number { | ||
return this.strategy.caculateTax(amount); | ||
} | ||
} | ||
|
||
function calculateByCounty(country: "USA" | "China", amount: number) { | ||
let strategy: TaxStrategy; | ||
switch(country) { | ||
case "USA": | ||
strategy = new USATaxStrategy(); | ||
break; | ||
case "China": | ||
strategy = new ChinaTaxStrategy(); | ||
break; | ||
default: | ||
throw new Error("not found"); | ||
} | ||
return new TaxCalculate(strategy).calculate(amount); | ||
} | ||
|
||
const calculateByUSA = calculateByCounty("USA", 10); | ||
console.log(calculateByUSA); | ||
|
||
const calculateByChina = calculateByCounty("China", 10); | ||
console.log(calculateByChina); | ||
``` | ||
|
||
::: |