成品网站怎么新建网页猎头用什么网站做单
web/
2025/10/8 18:32:28/
文章来源:
成品网站怎么新建网页,猎头用什么网站做单,什么网站专做外贸,企业网站的开发建设方案怎么写目录 1#xff0c;抽象类1#xff0c;为什么需要抽象类2#xff0c;抽象成员3#xff0c;设计模式-模板模式 2#xff0c;静态成员1#xff0c;什么是静态成员2#xff0c;设计模式-单例模式 1#xff0c;抽象类
1#xff0c;为什么需要抽象类
有时#xff0c;某个… 目录 1抽象类1为什么需要抽象类2抽象成员3设计模式-模板模式 2静态成员1什么是静态成员2设计模式-单例模式 1抽象类
1为什么需要抽象类
有时某个类只表示一个抽象的概念主要用于提取子类的公共成员而不是直接创建它的实例对象。此时这个类可以作为抽象类。
实现在类名前加 abstract抽象类不可以通过 new 来创建实例对象。
2抽象成员
有时一些公共成员是必须存在的但还不确定成员的值或具体实现。因为需要一种强约束让继承的子类必须实现这些成员。
也就是说抽象类中定义的抽象成员在子类中必须实现。
如果子类也是抽象类则可以不实现父类中的抽象成员或方法。
子类的3种实现方式
abstract class Chess {abstract readonly name: string;
}// 第1种
class Horse extends Chess {readonly name: string 马;
}// 第2种
class Pao extends Chess {readonly name: string;constructor() {super();this.name 炮;}
}// 第3种
class Soldier extends Chess {get name() {return 兵;}
}3设计模式-模板模式
当某个公共方法中一部分是公共逻辑一部分又是私有逻辑需要再子类中实现。
此时可以不将该方法定义为抽象方法而是将那部分私有逻辑定义为抽象方法并在当前方法中调用即可。
这样的强约束可以只关注子类需要实现的东西其他的父类已经完成。
abstract class Chess {abstract readonly name: string;move(targetX: number, targetY: number): boolean {// 第1和第2步属于公共逻辑// 1,边界条件判断// 2,目标位置是否有己方棋子// 第3步属于私有逻辑不同兵种的移动规则需要在子类中实现if (this.rule(targetX, targetY)) {console.log(移动成功);return true;} else {return false;}}protected abstract rule(targetX: number, targetY: number): boolean;
}class Horse extends Chess {protected rule(targetX: number, targetY: number): boolean {return true; // 简单实现做测试使用。}readonly name: string 马;
}const horse new Horse();
horse.move(2, 3);2静态成员
1什么是静态成员
指附着在类上的成员相当于构造函数的属性通过static修饰。 每个实例成员的相同属性理论上是不一样的所以那些相同的属性应该作为静态成员附着在类上。 构造函数或非静态方法中的this指向实例对象如果要访问当前类直接使用类名即可。
静态方法中的this指向当前类。
class User {static users: User[] [];constructor(public id: string, public pwd: string, public name: string, public age: number) {User.users.push(this);}static login(loginId: string, loginPwd: string): User | undefined {// 静态方法中 this 指向当前类return this.users.find((user) user.id loginId user.pwd loginPwd);}sayHello() {console.log(我是${this.name});}
}new User(u1, pwd1, 用户1, 18);
new User(u2, pwd2, 用户2, 188);console.log(User.users);const user User.login(u1, pwd1);
if (user) {user.sayHello();
}2设计模式-单例模式
某些类的实例对象在系统中只允许存在一个为了避免开发者随意创建实例对象而产生预期之外的错误可以使用单例模式进行强约束。 构造函数私有化或抽象类都不允许 new 实例对象。 class User {private constructor() {}private static _user?: User;static createUser() {if (!this._user) {this._user new User();}return this._user;}
}const u1 User.createUser();
const u2 User.createUser();
console.log(u1 u2);下面的方式也可以创建单例但有一些缺陷。
实例对象一开始就创建了不是在需要时才创建。做不到在创建单例对象时提前执行一些代码。
class User {private constructor() {}static readonly singleUser new User()
}const u1 User.singleUser;
const u2 User.singleUser;
console.log(u1 u2);以上。
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/web/89195.shtml
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!