在Android中应用委派模式的正确方法 [英] Correct way of applying delegation pattern in android

查看:59
本文介绍了在Android中应用委派模式的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的android应用程序中使用委托设计模式,但是不确定我是否正确执行了该设计模式。这是我的代码,用于 LoginActivity.java

I am trying to use the delegation design pattern in my android application but not sure whether I am doing it correctly or not. Here is my code for LoginActivity.java

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
    }
    public void login(View v) {
        AutoCompleteTextView emailInput = (AutoCompleteTextView) findViewById(R.id.email);
        EditText passwordInput = (EditText) findViewById(R.id.password);
        String email = emailInput.getText().toString();
        String password = passwordInput.getText().toString();
        new ConnectDatabase().authenticate(email, password);
    }

这是我的 ConnectDatabase.java 委托人

public class ConnectDatabase {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
    }
    public boolean authenticate(String email, String password) {
        Log.d("Message", email+" &"+password);
        return false;
    }

}

使用方法是否正确设计模式还是我必须创建一个接口,然后让 LoginActivity.java 实现它?

Is it the correct way of using the design pattern or I have to make a interface and then let the LoginActivity.java implement it?

推荐答案

您的代码正在委派,但IMO未使用 the 委派模式。

Your code is delegating but IMO not using "the" delegation pattern.

新的ConnectDatabase()。authenticate ... 可以简单地写为 ConnectDatabase.authenticate ,然后成为静态实用程序。您根本不需要任何对象。

new ConnectDatabase().authenticate... could simply be written as ConnectDatabase.authenticate and would then be a static utility mehod. You don't need an object at all.

来自 Wikipedia


对象而不是执行其陈述的任务之一,而是将该任务委托给关联的帮助对象。有一种责任倒置,其中称为委托者的助手对象被赋予执行委托者任务的责任。

an object, instead of performing one of its stated tasks, delegates that task to an associated helper object. There is an Inversion of Responsibility in which a helper object, known as a delegate, is given the responsibility to execute a task for the delegator.

我认为,当上述内容声明您委托给关联对象时,您需要在字面上加一点。因为,因为对象需要有成为对象的理由,所以它们需要承担责任,需要封装某些东西。例如,它可以为您跟踪某些状态,并从活动中隐藏一些复杂的状态机逻辑。创建帮助器并扔到同一行中时,这两个对象之间也没有关联。

I would argue that you need to take it a little more literally when above states that you delegate to an associated object. For one because objects need to have a reason to be objects, they need a responsibility, they need to encapsulate something. It could for example keep track of some state for you and hide some complex state machine logic from your Activity. There is also no association between those two objects when the helper is created and thrown away in the same line.

这篇关于在Android中应用委派模式的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆