深入浅出Objective-C笔记(一)

面向对象基础


对象
  • 对象:一个对象就是一个实体 ,人,鸟,铅笔,银行账户

  • 抽象:跟程序相关的东西抽取出来,是一种有选择的简化
    typedef_People{
    douoble height;
    double weight;
    }People;

    People p;     
    

注意:结构体不是对象,变量P才是对象。

  • 对象就是对一个实体的抽象和简化

  • 以上的列子只是静态的,还需对动态行为进行抽象。

  • 对象是对一个实体的静态属性和动态行为的抽象。

  • 对象=属性+行为 (思想)

    typedef_People{
      double height;
      double weight;}People ;
    void Squat(People *people);
    void Stand(People *people);
    
  • 为了区别面向过程中的函数,所以给函数起新名字就为面向对象的方法

  • 对象=数据+方法 (代码)


消息传递机制
  静态数据:
  typedef_BankAccount{
    double money;
    const char *password;
  }BankAccount;

  typedef_Costom{
    const char *password;
  }Custom;

  动态行为:
  const char *inputPassword ( Custom *custom )
  {
    return custom -> password;
  } //客户输入密码,返回客户的密码

  int validatePassword ( BankAccount *account, Custom *custom )
  {
    return strcmp ( account -> password, inputPassword ( custom ) );
  } //银行验证密码,调用客户密码,让它来和账户密码进行比对

  void deposit(BankAccount *account, Custom *custom, double money)
  {
    if( 0 == validatePassword ( account, custom) )
    {
      account -> money += money;
    } //存款功能。验证账户密码和顾客输入密码是否一致,如果一致则可存钱

  void withdraw ( BankAccount *account, Custom *custom, double money )
  {
    if ( 0 == validatePassword ( account, custom ) )
    {
      account -> money -= money;
    }
  } // 取款功能。验证账户密码跟顾客输入密码是否一致,若果一致则取钱。

动静结合起来当做类来看:

顾客类

typedef_Custom {
  const char *password;
} Custom;
const char *inputPassword ( Custom *custom );

账户类

typedef_BankAccount {
  double money;
  const char *password;
} BankAccount;
int validatePassword ( BankAccount *account, Custom *custom );
void deposit ( BankAccount *account, Custom *custom, double money );
void withdraw ( BankAccount *account, Custom *custom, double money );   

整个取款的流程 (消息传递)

Custom custom;
BankAccount account;
//  首先定义两个对象,顾客对象跟账户对象

withdraw ( &account, &custom, 100.0 );
// 顾客要取钱,就调用账户的withdraw方法,这就是第一次消息传递

inputPassword ( &custom );
//账户内部又向顾客传递消息,要求顾客输入密码

validatePassword ( &account, inputPassword ( &custom ) );
//顾客输入密码后,账户向自身发送消息,要求验证顾客输入的密码是否和账户的密码一致,(对象确实是可以向自己发送消息的)

消息传递机制:一个对象向另一个对象发送一条消息,接收消息的对象会根据收到的消息触发自己相应的方法。


  • 类是具有共同特征的对象的抽象。

  • 对象是类的实例。

  • 以下代码块就是一个类
    typedef_BankAccount {
    double money;
    const char *password;
    } BankAccount;
    int validatePassword ( BankAccount *account, Custom *custom );
    void deposit ( BankAccount *account, Custom *custom, double money );
    void withdraw ( BankAccount *account, Custom *custom, double money );

  • 结构体本身不是对象,用结构体声明出来的实例变量才是对象。


小结
  • 对象就是对实体静态属性跟动态行为的抽象,对应到程序里就是数据加方法。

  • 对象是一组数据和在数据上操作的封装。

  • 对象间通过消息传递机制完成交互。

  • 类是具有共同特征对象的抽象,一般用于制作同一类型的对象。

你可能感兴趣的:(深入浅出Objective-C笔记(一))