在不同的类中使用一个类(基本的 oop 理解)?

基督教

我已经使用 ruby​​ 工作了很长时间,但我在使用面向对象的方法时有点卡住了。我已经阅读了关于对象、类、可靠原则和一些教程的内容,但这些通常只提供一个类,就像在这个介绍中一样(滚动到页面的最底部)。

这是来自链接网站的示例。

我的问题是如何实现另一个类,让我们说一个 Client 最好?

class ClientAccount                                   
  attr_accessor(:id,:limit)                           

  def initialize(id, money, limit)                    
    @id = id                                          
    @money = money                                    
    @limit = limit                                    
  end                                                 

  def below_limit?(limit)                             
    self.money < limit                                
  end

  def alert                                           
    if below_limit?(limit)                            
      puts 'Client has no more money.'                
    else                                              
      puts 'Everything is fine'                       
    end                                               
  end                                                 

  protected                                           

  attr_accessor(:money)                               
end

我想要做的是添加一个或多个类,例如下面的客户端类,它与第一个类进行交互,例如:

account = ClientAccount.new('x234x19ue24', -245, -150)
id = account.read
client = Client.new('X 先生', '1.1.1900', id )

这不可能是正确的方法......

这是我的 Client 类的想法,我要么将整个对象放在构造函数中(或作为参数),要么尝试创建一个单例(?)...

class Client
  def initialize(name, date_of_birth)
    @name = name
    @date_of_birth = date_of_birth
    @account_id = account_id
  end

  private

  def account
    How can I access the ClientAccount here? Is this the correct way?
  end
end

如果我们添加第三个类,例如类 ClientXYZ,则更复杂,但对于这个例子,两个可能已经足够了......

正如你所看到的,非常基本的东西,我想更多地了解几个类之间的联系。目前,我自己的代码通常感觉像是带有某些对象的过程代码。我确信有几种方法,但我真的错过了一个中等级别的例子。与上面的代码相关,如何将account.read方法引入Client类来填充account_id。

PS你能举个例子吗?在处理代码时我可以做什么?或者甚至推荐一个关于这个的好教程?

阿兹巴恰

要使其与您开发它的方式保持一致,请尝试:

class Client
  def initialize(name, date_of_birth, account)
    @name = name
    @date_of_birth = date_of_birth
    @account = account
  end

  private

  def account
    @account
  end

  public

  def alert_on_account
    account.alert
  end
end

我还建议您阅读github 上免费提供的一些教程

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章