export default abstract class AbstractDisplay { public abstract open(): void; public abstract print(): void; public abstract close(): void; public display(): void { this.open(); for (let i = 0; i < 5; i++) { this.print(); } this.close(); } }
CharDisplay类:打印方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
import AbstractDisplay from "./AbstractDisplay";
export default class CharDisplay extends AbstractDisplay { private ch: string;
constructor(ch: string) { super(); this.ch = ch; } public open() { console.log("《"); } public print() { console.log(this.ch); } public close() { console.log("》"); } }
StringDisplay类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
import AbstractDisplay from "./AbstractDisplay";
export default class StringDisplay extends AbstractDisplay { private str: string; constructor(str: string) { super(); this.str = str; } public open() { console.log("+-----+"); } public print() { console.log(`|${this.str}|`); } public close() { console.log("+-----+"); } }
main函数
1 2 3 4 5 6 7 8
import AbstractDisplay from "./AbstractDisplay" import CharDisplay from "./CharDisplay" import StringDisplay from "./StringDisplay";
const d1: AbstractDisplay = new CharDisplay("H"); const d2: AbstractDisplay = new StringDisplay("Hello") d1.display(); d2.display();
输出
1 2 3 4 5 6 7 8 9 10 11 12 13 14
《 H H H H H 》 +-----+ |Hello| |Hello| |Hello| |Hello| |Hello| +-----+