2、面向对象 VS 面向过程
1、面向过程编程语言
struct User {
char name[64];
int age;
char gender[16];
};
struct User parse_to_user(char *text) {
// 将 text("小王\t28\t 男") 解析成结构体 struct User
}
char *format_to_text(struct User user) {
// 将结构体 struct User 格式化成文本 text("小王\t28\t 男")
}
void sort_users_by_age(struct User users[]) {
// 按照年龄从小到大排序 users
}
void format_user_file(char *origin_file_path, char *new_file_path) {
// open files ...
struct User users[1024]; // 假设最大 1024 个用户
int count = 0;
// read until the file is empty
while (1) {
struct User user = parse_to_user(line);
users[count++] = user;
}
sort_users_by_age(users);
for (int i = 0; i < count; ++i) {
char *formatted_user_text = format_to_text(users[i]);
// write to new file ...
}
// close files ...
}
int main(void) {
format_user_file("/home/zheng/user.txt", "/home/zheng/formatted_users.txt");
}
2、面向对象编程语言
public class User {
private String name;
private int age;
private String gender;
public User(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
public static User parseFrom(String userInfoText) {
// 将 text("小王\t28\t男") 解析成类 User
}
public String formatToText() {
// 将类 User 格式化成文本 text("小王\t28\t男")
}
}
public class UserFileFormatter {
public void format(String userFile, String formattedUserFile) {
// Open files ...
List users = new ArrayList<>();
// read until file is empty
while (1) {
// read from file into userText ...
User user = User.parseFrom(userText);
users.add(user);
}
// sort users by age ...
for (int i = 0; i < users.size(); ++i) {
String formattedUserText = user.formatToText();
// write to new file ...
}
// close files ...
}
}
public class MainApplication {
public static void main(String[] args) {
UserFileFormatter userFileFormatter = new UserFileFormatter();
userFileFormatter.format("/home/zheng/users.txt", "/home/zheng/formatted_users.txt");
}
}
3、面向对象编程的优势
- 对于大规模复杂程序的开发,程序的处理流程并非单一的一条主线,而是错综复杂的网状结构
面向对象编程比起面向过程编程,更能应对这种复杂类型的程序开发 - 面向对象编程相比面向过程编程,具有更加丰富的特性(封装、抽象、继承、多态)
利用这些特性编写出来的代码,更加易扩展、易复用、易维护 - 从编程语言跟机器打交道的方式的演进规律中,我们可以总结出:面向对象编程语言比起面向过程编程语言,更加人性化、更加高级、更加智能
本文来自博客园,作者:lidongdongdong~,转载请注明原文链接:https://www.cnblogs.com/lidong422339/p/17501253.html