首页 > web前端 > js教程 > 正文

面向对象编程——封装

碧海醫心
发布: 2024-12-01 09:03:09
转载
1134人浏览过

面向对象编程——封装

什么???

封装是将数据和函数捆绑到一个单元(即胶囊)中的过程,它还可以限制对某些数据/方法的访问。

它是 oop 的四大支柱之一,其他三者分别是继承、多态性和数据抽象。

为什么

采取盲目假设并在所有地方继续使用封装会更容易,但了解原因很重要,这样您才能以正确的方式使用它。

让我们尝试通过查看示例任务来理解原因。

任务:

构建一个学生成绩计算器,

  • 计算平均分
  • 确定学生是否失败或通过
  • 如果任何主题标记无效,则抛出错误 ( < 0 || > 100)

方案一:非封装方式

这个想法只是为了解决问题,所以我选择了过程式编程实现它的方式,我相信它可以显示出很好的对比并使问题看起来更明显。

type subject = "english" | "maths";

interface istudent {
  name: string;
  marks: record<subject, number>;
}

// receive input
const studentinput: istudent = {
  name: "john",
  marks: {
    english: 100,
    maths: 100,
  },
};

// step1: validate the provided marks
object.keys(studentinput.marks).foreach((subjectname) => {
  const mark = studentinput.marks[subjectname as subject];
  if (mark > 100 || mark < 0) {
    throw new error(`invlid mark found`);
  }
});

// step2: find the total marks
const totalmarks = object.keys(studentinput.marks).reduce(
  (accumulator: number, current: string) =>
    studentinput.marks[current as subject] + accumulator,
  0
);

// step3: find the average
const average = totalmarks / object.keys(studentinput.marks).length;

// step4: find the result
const boolresult = average > 40;

// step 5: print result
console.log(boolresult);
console.log(average);

登录后复制

解决方案 1 的问题:

AI封面生成器
AI封面生成器

专业的AI封面生成工具,支持小红书、公众号、小说、红包、视频封面等多种类型,一键生成高质量封面图片。

AI封面生成器 108
查看详情 AI封面生成器

这确实达到了预期的结果,但也存在一些与之相关的问题。仅举几例,

  1. 这里的每个实现都是全局可访问的,并且未来的贡献者无法控制其使用。
  2. 数据和操作是分开的,因此很难追踪哪些函数影响数据。您必须仔细检查每一段代码才能了解调用的内容以及执行的一部分。
  3. 随着逻辑的扩展,函数变得更难管理。由于紧密耦合,更改可能会破坏不相关的代码。

如何解决问题?

通过合并封装或通过执行以下两个步骤使其更加明显,

  1. 对数据和功能的受控访问
  2. 将数据与行为捆绑

解决方案2:封装方式

type SubjectNames = "english" | "maths";

interface IStudent {
  name: string;
  marks: Record<SubjectNames, number>;
}

class ResultCalculator {
  protected student: IStudent;
  constructor(student: IStudent) {
    this.student = student;
  }

  isPassed(): boolean {
    let resultStatus = true;
    Object.keys(this.student.marks).forEach((subject: string) => {
      if (this.student.marks[subject as SubjectNames] < 40) {
        resultStatus = false;
      }
    });
    return resultStatus;
  }

  getAverage(): number {
    this.validateMarks();
    return this.totalMarks() / this.subjectCount();
  }

  private validateMarks() {
    Object.keys(this.student.marks).forEach((subject: string) => {
      if (
        this.student.marks[subject as SubjectNames] < 0 ||
        this.student.marks[subject as SubjectNames] > 100
      ) {
        throw new Error(`invalid mark`);
      }
    });
  }

  private totalMarks() {
    return Object.keys(this.student.marks).reduce(
      (acc, curr) => this.student.marks[curr as SubjectNames] + acc,
      0
    );
  }

  private subjectCount() {
    return Object.keys(this.student.marks).length;
  }
}

// Receive Input
const a: IStudent = {
  name: "jingleheimer schmidt",
  marks: {
    english: 100,
    maths: 100,
  },
};

// Create an encapsulated object
const result = new ResultCalculator(a);

// Perform operations & print results
console.log(result.isPassed());
console.log(result.getAverage());

登录后复制

注意上述解决方案,

  1. 方法totalmarks、subjectcount、validatemarks 和成员变量student 不公开,只能由类对象使用。

2.数据学生与其每一个行为都捆绑在一起。

以上就是面向对象编程——封装的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:dev.to网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号