简体   繁体   English

如何更好地随机化 Java 中的方法调用(不重复类似的行)?

[英]How to better randomize method calls in Java (without repeating similar lines)?

I have this file as an example of a Pet app for Android that showcases profiles of cats or dogs (courtesy of a Udemy course).我将此文件作为 Android 的宠物应用程序示例,该应用程序展示了猫或狗的个人资料(由 Udemy 课程提供)。 this is the base file:这是基本文件:

package com.delta.generics;

import android.app.Activity;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pManager;
import android.os.Bundle;
import android.service.dreams.DreamService;
import android.util.StringBuilderPrinter;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class GenericsActivity extends Activity {

    public TextView nameTextView = null;
    public TextView descriptionTextView = null;
    public RatingBar ratingView = null;
    public ImageView portraitView = null;
    public Button nextButton = null;

    private int currentSelection = 0;

//    CatAdapter catAdapter;
    AdoptAdapter<Cat> catAdoptAdapter;
//    AdoptAdapter<Dog> dogAdoptAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_generics);

        nameTextView = (TextView) findViewById(R.id.nameTextView);
        descriptionTextView = (TextView) findViewById(R.id.descriptionTextView);
        ratingView = (RatingBar) findViewById(R.id.ratingView);
        portraitView = (ImageView) findViewById(R.id.portraitView);
        nextButton = (Button) findViewById(R.id.nextButton);
        nextButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showNext();
            }
        });

//        commenting this out in favour of AdoptAdapter objects
//        catAdapter = new CatAdapter(this,nameTextView,descriptionTextView,ratingView,portraitView);
//        catAdapter.set(AdoptData.mCatList.get(0));

        catAdoptAdapter = new AdoptAdapter<Cat>(this, nameTextView, descriptionTextView, ratingView, portraitView);
//        dogAdoptAdapter = new AdoptAdapter<Dog>(this, nameTextView, descriptionTextView, ratingView, portraitView);

        catAdoptAdapter.set(AdoptData.mCatList.get(0));
//        dogAdoptAdapter.set(AdoptData.mDogList.get(0));
        // mCatList and mDogList is an object already exists in AdoptData.java

    }

    public void showNext(){
        int random = currentSelection;
        int animal_random = 0;
        animal_random = (int )(Math.random() * 2;
        while(random == currentSelection){
            //avoid same selection twice.
            random = (int )(Math.random() * AdoptData.mCatList.size());
            random = (int )(Math.random() * AdoptData.mDogList.size());
        }
        currentSelection = random;
        Cat c = AdoptData.mCatList.get(random);
//        Dog d = AdoptData.mDogList.get(random);
//        commenting in favour of AdoptAdapter object
//        catAdapter.set(c);
        catAdoptAdapter.set(c);
//        dogAdoptAdapter.set(d);
        
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.generics, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }



}

在此处输入图像描述

The issue I see is that the way this is formatted, it can only either showcase Cat or Dog profiles, but not together, and I wanted to figure out a way of how to "mix" them so both Cats and Dogs shows up randomly when pressing the "Next" button.我看到的问题是它的格式化方式,它只能展示 Cat 或 Dog 的个人资料,但不能一起展示,我想弄清楚如何“混合”它们,以便 Cats 和 Dogs 随机出现按“下一步”按钮。 And so I figured within the context of Java and this file, I figured I can modify the showNext() method:所以我想在 Java 和这个文件的上下文中,我想我可以修改showNext()方法:

    public void showNext(){
        int random = currentSelection;
        int animal_random = 0;
        animal_random = (int )(Math.random() * 2);
        Log.e("animal_random", String.valueOf(animal_random));
        switch(animal_random){
            case 0:
                while(random == currentSelection){
                    //avoid same selection twice.
                    random = (int )(Math.random() * AdoptData.mCatList.size());
                }
                currentSelection = random;
                Cat c = AdoptData.mCatList.get(random);
                catAdoptAdapter.set(c);
                break;
            case 1:
                while(random == currentSelection){
                    //avoid same selection twice.
                    random = (int )(Math.random() * AdoptData.mDogList.size());
                }
                currentSelection = random;
                Dog d = AdoptData.mDogList.get(random);
                dogAdoptAdapter.set(d);
                break;

        }
    }

But I feel like there are way too many "repeated lines" here.但我觉得这里的“重复行”太多了。 If this were in Python I would probably utilize the getAttribute() method to determine which method to use in the object based on a string match.如果这是在 Python 中,我可能会利用getAttribute()方法根据字符串匹配确定在 object 中使用哪种方法。 However when I tried to use the supposed Java equivalent getMethod() i keep getting a java.lang.NoSuchMethodException error when i try to use it.但是,当我尝试使用假定的 Java 等效getMethod()时,当我尝试使用它时,我不断收到java.lang.NoSuchMethodException错误。

Is there a better way to go about this in Java...?在 Java ... Or would it require a complete restructure for this specific example?或者是否需要对这个特定示例进行全面重组?

Once you've picked any of the two alternatives below, just update the rest of your code and you'll probably see less duplication across the board since the animals will have a common ground somewhere.一旦您选择了以下两个替代方案中的任何一个,只需更新您的代码的 rest,您可能会看到全面的重复减少,因为这些动物将在某个地方有共同点。 :-) :-)

The interface way 接口方式

Create an Animal interface that gives you access to the common things for animals in your given case, and then implement the interface in both your Dog and your Cat class.创建一个Animal接口,让您可以在给定的情况下访问动物的常见事物,然后在您的DogCat class 中实现该接口。 Your code in question will probably mostly be talking about Animal s instead, unless you explictly need to differentiate between a Dog or a Cat in some way.除非您明确需要以某种方式区分DogCat ,否则您有问题的代码可能主要是在谈论Animal

One of the neat things about this approach is that while the interface will enforce a contract, it also gives you the wiggle room for if you example want the Dog class to be able to contain stuff that the Cat shouldn't.这种方法的好处之一是,虽然界面将强制执行合同,但它也为您提供了回旋余地,例如,如果您希望Dog class 能够包含Cat不应该包含的内容。 Maybe it already does?也许它已经做到了?

The enum way枚举方式

Consolidate your Dog and Cat classes into a single Animal class that carries an enum field called type or something like that.将您的DogCat类合并到一个Animal class 中,该类带有一个名为type或类似名称的enum字段。 Less classes (hurray?), but with the caveat that the dogs, cats and whatever future animals you add kinda have to fit into the same data structure.更少的类(欢呼?),但需要注意的是,狗、猫和您添加的任何未来动物都必须适应相同的数据结构。 Depending on how much weight and meaning the actual type of animal actually has, this may or may not be a really bad idea.根据动物的实际类型实际具有多少重量和意义,这可能是也可能不是一个非常糟糕的主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM