0
我想从一组类中创建对象,而不必定义每个集合...实质上,我试图创建装饰器模式。在打字稿中,由于编辑限制,这似乎几乎不可能。如何在打字稿中创建装饰模式?
我试过使用代理。没有骰子。
以下是我正在尝试完成的用法(某些代码缺失以允许我正在尝试执行的操作 - 这是我正在尝试解决的问题)。
class Person {
public name:string;
public age:number;
public identify(){
console.log(`${this.name} age ${this.age}`);
}
}
class Child {
public Mother:Person;
public Father:Person;
public logParents(){
console.log("Parents:");
this.Mother.identify();
this.Father.identify();
}
}
class Student {
public school:string;
public logSchool(){
console.log(this.school);
}
}
let Dad = new Person();
Dad.name = "Brad";
Dad.age = 32;
let Mom = new Person();
Mom = new Student(Mom);
Mom.name = "Janet";
Mom.age = 34;
Mom.school = "College of Night School Moms";
let Johnny = new Person();
Johnny = new Child(Johnny);
Johnny = new Student(Johnny);
Johnny.name = "Johnny";
Johnny.age = 12;
Johnny.Mother = Mom;
Johnny,Father = Dad;
Johnny.school = "School for kids who can't read good";
(约翰尼如儿童).logParents()不会在这里工作。 – Bradley
没错。我错过了,在java例子中他们有私有方法而不是公共方法,这就是为什么它不是问题。但是这个问题存在于java中,可能还有其他OO语言。基本上你正在寻找与mixin的装饰模式。在typescript/javascript中,这可能比使用或不使用代理服务器的可能性要大,但我怀疑它可能有点矫枉过正,至少在大多数情况下是这样。你的场景是什么?你的代码只是你问题的一个例子,还是你真正的模型? –
这只是一个简单的例子。真正的场景还有更多...基本上是一系列“扩展”的基础对象,可以在任意数量的组合中进行混合和匹配。 – Bradley