Java 如何重用方法?

Java 如何重用方法?,java,function,methods,delegates,Java,Function,Methods,Delegates,我是一个初学者,我试着自学干净的编码。我想把一个函数作为一个参数传递,这样我就可以重用一个方法而不必重复代码。我举了一个例子: public class Dog { private String name; private int id; private List<String> characteristic; public List<String> getCharacteristic() { return charact

我是一个初学者,我试着自学干净的编码。我想把一个函数作为一个参数传递,这样我就可以重用一个方法而不必重复代码。我举了一个例子:

public class Dog {
    private String name;
    private int id;
    private List<String> characteristic;

    public List<String> getCharacteristic() {
        return characteristic;
    }

    public void setCharacteristic(List<String> characteristic) {
        this.characteristic = characteristic;
    }
 }

public class Check{
    private List<Dog> dogs = new ArrayList();

    public void iterate() {
        while (dogs.size() > 0) {
            for (Dog dog : dogs) {
                List<String> restChara = new ArrayList<>();
                restChara= checkChara(dog, restChara);
                if (restChara.size()>0) {
                    dog.setCharacteristic(restChara);
                } else {
                    dogs.remove(dog);
                }
            }
        }
    }

    private List<String> checkChara(Dog dog, List<String> restChara) {
        for (String chara : dog.getCharacteristic()) {
            boolean charaChecked = doSomething(chara);
            if (!charaChecked) {
                restChara.add(chara);
            } else {
                dog.getCharacteristic().remove(chara);
            }
        }
        return restChara;
    }

    private boolean doSomething(String chara){
        //do sth.
        return true;
    }
    private boolean doSomething2(String chara){
        //do sth.
        return true;
    }
}
公共级狗{
私有字符串名称;
私有int-id;
私有列表特性;
公共列表getCharacteristic(){
回波特性;
}
公共特征(列表特征){
这个特性=特性;
}
}
公共类检查{
private List dogs=new ArrayList();
公共void iterate(){
而(dogs.size()>0){
用于(狗:狗){
List restChara=new ArrayList();
restChara=checkChara(狗,restChara);
if(restChara.size()>0){
狗的刚毛特征(restChara);
}否则{
狗。移除(狗);
}
}
}
}
私人列表checkChara(Dog Dog,List restChara){
for(字符串字符:dog.getCharacteristic()){
布尔字符=doSomething(字符);
如果(!已选中){
添加(字符);
}否则{
dog.getCharacteristic().remove(chara);
}
}
返回restChara;
}
私有布尔doSomething(字符串字符){
//做某事。
返回true;
}
私有布尔值doSomething2(字符串字符){
//做某事。
返回true;
}
}
为了在其中使用不同的函数,您将如何定义checkChara方法

我的第一个想法是将函数作为参数传递(我想它应该是在C#委托中)

多谢各位

编辑:

我想我找到了另一种模式策略设计模式


我不太明白你的意思,但我想可能是这样的:

List<Runnable> runMyStuff = new ArrayList<Runnable>();
        String variable= "Hallo"; //needs to be effectively final 
        runMyStuff.add(() -> {
            System.out.println(variable);
            doSomething(variable);

        });

        runMyStuff.add(() ->{
            System.out.println("This is a test");
        });

        runMyStuff.add(() ->{
            System.out.println("2 + 2 = " + (2+2) );
        });

        runMyStuff.get(0).run();
        runMyStuff.get(2).run();
        runMyStuff.get(0).run();
        runMyStuff.get(1).run();
        runMyStuff.get(2).run();

当您在这些可运行的方法中放置变量或传递参数时,它们需要是有效的final,或者您在容器中传递它们。 您可以重新运行每个方法。 在这些方法中,您可以执行其他方法

注意: 如果您想要返回参数,可以使用Callable和than“.call()”而不是run执行相同的操作

编辑: 假设你是说性格检查之类的 带接口的CharCheck passable方法示例:

    public interface CharacterChecker{
        //is a template returns boolean, need a String param
        public boolean call(String chara);

    }
执行“CHaracterChecker”类型的PASS方法的方法

“字符检查器”的两种不同实现

传递给“方法”的方法(更像是带有该方法的匿名OS类对象)

结果将是:

bad: false
good: true
jolly: false
frisky: false
lazy: true

Java不支持“直接”嵌套方法。许多函数式编程语言支持方法中的方法。但您可以在Java7或更早的版本中通过定义本地类来实现嵌套方法功能,方法中的类就是这样编译的。在Java8和更新版本中,您可以通过lambda表达式实现它

方法1(使用匿名子类)

它是一个没有名称的内部类,只为其创建一个对象。匿名内部类在创建具有某些“附加”的对象实例时非常有用,例如重载类或接口的方法,而不必实际对类进行子类化

//Java program implements method inside method 
public class GFG { 

// create a local interface with one abstract 
// method run() 
interface myInterface { 
    void run(); 
} 

// function have implements another function run() 
static void Foo() 
{ 
    // implement run method inside Foo() function 
    myInterface r = new myInterface() { 
        public void run() 
        { 
            System.out.println("geeksforgeeks"); 
        }; 
    }; 
    r.run(); 
} 
public static void main(String[] args) 
{ 
    Foo(); 
} 
} 
方法2(使用本地类) 还可以在本地类内实现方法。在方法内部创建的类称为局部内部类。如果要调用本地内部类的方法,必须在方法内实例化该类

// Java program implements method inside method 
public class GFG { 

// function have implementation of another  
// function inside local class 
static void Foo() 
{ 
    // local class 
    class Local { 
        void fun() 
        { 
            System.out.println("geeksforgeeks"); 
        } 
    } 
    new Local().fun(); 
} 
public static void main(String[] args) 
{ 
    Foo(); 
} 
} 
方法3(使用lambda表达式) Lambda表达式基本上表示函数接口的实例(具有单个抽象方法的接口称为函数接口。示例为java.lang.Runnable)。lambda表达式实现唯一的抽象函数,因此实现函数接口

// Java program implements method inside method 
public class GFG { 
interface myInterface { 
    void run(); 
} 

// function have implements another function 
// run() using Lambda expression 
static void Foo() 
{ 
    // Lambda expression 
    myInterface r = () -> 
    { 
        System.out.println("geeksforgeeks"); 
    }; 
    r.run(); 
} 
public static void main(String[] args) 
{ 
    Foo(); 
} 
} 

您可以通过在代码中的不同位置调用方法来重用这些方法,还有其他方法吗?好的,对不起,这没有清楚地表达出来。您是在问Java lambdas吗?或者什么?是的,lambda或interfaces,我不知道如何以最简单的方式实现这一点,但我也可以简单地在方法中添加一个switch case,并传递一个int,以便执行某个方法。但我希望其他开发人员能够调用该方法并将函数作为parameter@Kleinstein11“其他开发人员传递函数”是什么意思?我建议使用接口。可能他们还可以向列表中添加自己的可运行方法,并在以后运行它们。你也可以用地图之类的东西。但我不推荐以这种方式传递函数。最好使用接口。你能给我举一个如何用接口解决上述问题的例子吗?我从来没有真正理解过这件事xD@Kleinstein11我建议深入研究接口,因为这对于“模板化”某些类型的对象来说是非常有用和重要的。在你的情况下,你想在CheckChara中有一个不同的“doSomething”。但您只需要布尔类型的返回值。所以你可以使用一个“Callable”来传递给“CheckChara”。
bad: false
good: true
jolly: false
frisky: false
lazy: true
//Java program implements method inside method 
public class GFG { 

// create a local interface with one abstract 
// method run() 
interface myInterface { 
    void run(); 
} 

// function have implements another function run() 
static void Foo() 
{ 
    // implement run method inside Foo() function 
    myInterface r = new myInterface() { 
        public void run() 
        { 
            System.out.println("geeksforgeeks"); 
        }; 
    }; 
    r.run(); 
} 
public static void main(String[] args) 
{ 
    Foo(); 
} 
} 
// Java program implements method inside method 
public class GFG { 

// function have implementation of another  
// function inside local class 
static void Foo() 
{ 
    // local class 
    class Local { 
        void fun() 
        { 
            System.out.println("geeksforgeeks"); 
        } 
    } 
    new Local().fun(); 
} 
public static void main(String[] args) 
{ 
    Foo(); 
} 
} 
// Java program implements method inside method 
public class GFG { 
interface myInterface { 
    void run(); 
} 

// function have implements another function 
// run() using Lambda expression 
static void Foo() 
{ 
    // Lambda expression 
    myInterface r = () -> 
    { 
        System.out.println("geeksforgeeks"); 
    }; 
    r.run(); 
} 
public static void main(String[] args) 
{ 
    Foo(); 
} 
}