java 行为参数化_Java中的行为参数化

java 行为参数化

The past isn’t here anymore, the future cannot be seen and the only thing permanent is the present moment and nothing else. Everything is the result of the change. There is nothing to question — change is the only constant in the life.

过去不再在这里,未来不可见,唯一的永恒是现在,而没有别的。 一切都是变化的结果。 毋庸置疑-变化是生活中唯一的常数。

A well-known and most irritating problem software industry is that no matter what we do, customer requirements will always be changed. For example, suppose you are developing an application to help your customer to understand his Employee. Your customer might want an API in your application to find all the employees who are older than 50 years. But the next day he might tell you, “Actually I also want to find all employees who are Manager.” Two days later, the same customer comes back and adds something new like “It would be really great if I could find all employees who is Manager and older than 50 years.” How can you manage these changing requirements for application?

一个众所周知且最令人困扰的问题软件行业是,无论我们做什么,客户需求都将不断变化。 例如,假设您正在开发一个应用程序来帮助您的客户了解其雇员。 您的客户可能希望应用程序中的API查找所有50岁以上的员工。 但是第二天他可能会告诉您:“实际上,我也想找到所有经理人员。” 两天后,同一位客户回来并添加了新内容,例如“如果我能找到所有经理和50岁以上的员工,那将是非常不错的。” 您如何管理这些不断变化的应用程序需求?

Behavior parameterization is a software development pattern that lets you how to handle frequent requirement changes. Behavior parameterization adds an ability to a method to receive multiple different behaviors as its parameter and use them internally to accomplish the task.

行为参数化是一种软件开发模式,可让您如何处理频繁的需求变更。 行为参数化为方法添加了一种功能,使其能够接收多种不同的行为作为其参数,并在内部使用它们来完成任务。

Let’s walk through an example and go through the Java code in the context of an EmployeeInfo application,

让我们来看一个示例,并在EmployeeInfo应用程序的上下文中浏览Java代码

We have to implement an API to categorize employees who are from India.

我们必须实现一个API,对来自印度的员工进行分类。

  1. Naive and Simple Approach

    天真而简单的方法

private static List<Employee> getIndiaEmp(List<Employee> empList) {
        List<Employee> result = new ArrayList<>();//An Accumulator List for Employee
        for(Employee emp : empList){
            if(emp.getCountry().equals("IN")){        // Filter, Select only Older employee
                result.add(emp);
            }
        }
        return result;
    }

But now the Customer changes his mind and wants to also get employees from other countries like the US, Germany, What can we do? The easiest solution would be to duplicate the above method getIndiaEmp, rename it as getUsemp(), and getGermanEmp(), But this approach doesn’t look good. Might be your customer has some other filter on the age.

但是现在,客户改变了主意,还希望从美国,德国等其他国家/地区招募员工,我们该怎么办? 最简单的解决方案是复制上述方法getIndiaEmp,将其重命名为getUsemp()和getGermanEmp(),但是这种方法看起来不太好。 可能是您的客户在年龄上有其他过滤条件。

2. Parameterizing the Address(Country)

2.参数化地址(国家)

What we can do is add a country as a parameter to the method to parameterize and be more flexible to such changes.

我们可以做的是将国家/地区作为参数添加到方法中,以进行参数设置并更灵活地应对此类更改。

private static List<Employee> getEmpByCountry(List<Employee> empList, String country) {
        List<Employee> result = new ArrayList<>();
        for(Employee emp : empList){
            if(emp.getCountry().equals(country)){
                result.add(emp);
            }
        }
        return result;
    }

We can now make the customer happy and call our method as belowList<Employee> usEmp = getEmpByCountry(empList,”US”);List<Employee> germanEmp = getEmpByCountry(empList,”GER”);List<Employee> indiaEmp = getEmpByCountry(empList,”IN”);

现在,我们可以使客户满意并调用以下方法:List <Employee> usEmp = getEmpByCountry(empList,“ US”); List <Employee> germanEmp = getEmpByCountry(empList,“ GER”); List <Employee> indiaEmp = getEmpByCountry( empList,“ IN”);

Suppose the same customer comes back says, We need to differentiate employees by age as older(age>40) and younger(age<40).A naive and simple solution is we can rename the above method getEmpByCountry() as getEmpByAge() with parameter employee list and age getEmpByAge(List<Employee>, age) but here most of codes are duplicate.

假设同一位客户回来说,我们需要按年龄(年龄大于40岁)和年龄小于40岁(年龄小于40岁)的不同来区分员工。天真而简单的解决方案是,可以将上述方法getEmpByCountry()重命名为getEmpByAge(),参数员工列表和年龄getEmpByAge(List <Employee>,age),但是此处大多数代码重复。

Now to eliminate the above problem like continuous requirement changes, a lot of duplicate codes, etc. We need to introduce a better level of abstraction.

现在,要消除上述问题,例如连续的需求变更,大量重复的代码等,我们需要引入更好的抽象级别。

3. Behavior parameterization using Different Strategies (Interface)

3.使用不同策略的行为参数化(接口)

We can create an interface

我们可以创建一个界面

interface EmployeePredicate{
     public boolean test(Employee employee);
}

We can create different type of predicates like

我们可以创建不同类型的谓词,例如

class USEmpPredicate implements EmployeePredicate{
    @Override
    public boolean test(Employee employee) {
        return employee.getCountry().equals("US");
    }
}
class OlderEmpPredicate implements EmployeePredicate{
    @Override
    public boolean test(Employee employee) {
        return employee.getAge()>50;
    }
}

Now we can create a new method filterEmp(List<Employee>, EmployeePredicate) as below

现在,我们可以如下创建一个新方法filterEmp(List <Employee>,EmployeePredicate)

private static List<Employee> filterEmp(List<Employee> empList, EmployeePredicate p){
        List<Employee> result  = new ArrayList<>();
        for(Employee emp : empList){
            if(p.test(emp)){
                result.add(emp);
            }
        }
        return result;
    }

We can use this method like this

我们可以这样使用

List<Employee> usEmp = filterEmp(empList, new USEmpPredicate());

List <Employee> usEmp = filterEmp(empList,new USEmpPredicate());

[Employee{name=’Kumar’, add=’US’, designation=’Manager’, age=45}, Employee{name=’Kavi’, add=’US’, designation=’Manager’, age=25}]

[Employee {name ='Kumar',add ='US',designation ='Manager',age = 45},Employee {name ='Kavi',add ='US',designation ='Manager',age = 25} ]

We can create a new predicate for an older employee who is from India as below.

我们可以为来自印度的年长雇员创建一个新的谓词,如下所示。

class OlderIndianEmpPredicate implements EmployeePredicate{
    @Override
    public boolean test(Employee employee) {
        return employee.getAge()>50 &&
                employee.getCountry().equals("IN");
    }
}

We can use as below

我们可以如下使用

List<Employee> olderIndianEmp = filterEmp(empList, new OlderIndianEmpPredicate());[Employee{name=’Ram’, add=’IN’, designation=’Developer’, age=58}]

List <Employee> oldIndianEmp = filterEmp (empList,新的OlderIndianEmpPredicate()); [Employee {name ='Ram',add ='IN',designation ='Developer',age = 58}]

In this approach, We will have to write a lot of codes that introduces a lot of verbosities. To eliminate these verbosities we can use the java anonymous class.

在这种方法中,我们将不得不编写很多代码,引入很多详细信息。 为了消除这些冗长的细节,我们可以使用java匿名类。

4. Behavior parameterization using Anonymous classes

4.使用匿名类进行行为参数化

The following code shows how to rewrite the filtering example by creating an object that implements EmployeePredicate using an anonymous class.

以下代码显示如何通过创建使用匿名类实现EmployeePredicate的对象来重写过滤示例。

List<Employee> olderIndianEmp = filterEmp(empList, new EmployeePredicate() {
            @Override
            public boolean test(Employee employee) {
                return employee.getAge()>50 && employee.getCountry().equals("IN");
            }
        });
        System.out.println(olderIndianEmp);

5. Behavior parameterization using Lambda expression

5.使用Lambda表达式进行行为参数化

How can we write the above code using the lambda expression.

我们如何使用lambda表达式编写上面的代码

List<Employee> olderIndianEmp = filterEmp(empList, new EmployeePredicate() {
            @Override
            public boolean test(Employee employee) {
                return employee.getAge()>50 && employee.getCountry().equals("IN");
            }
        });
        System.out.println(olderIndianEmp);
        //Lambda expression
        //emp.getAge()>50 && emp.getCountry().equals("IN") behaviour as a parameter
        List<Employee> olderIndianEmp_lambdaExp = filterEmp(empList, (Employee emp)-> emp.getAge()>50 && emp.getCountry().equals("IN"));
        System.out.println(olderIndianEmp_lambdaExp);
List<Employee> olderIndianEmp_lambdaExp = filterEmp(empList, (Employee emp)-> emp.getAge()>50 && emp.getCountry().equals("IN"));

Now We can see that behavior parameterization is a useful pattern to easily adapt to changing requirements. This pattern lets you encapsulate a behavior (a piece of code) and parameterize the behavior of methods bypassing and using these behaviors you create.

现在,我们可以看到行为参数化是一种易于适应不断变化的需求的有用模式。 通过这种模式,您可以封装行为(一段代码)并参数化绕过和使用您创建的这些行为的方法的行为。

Behavior parameterization is the ability of a method to take multiple different behaviors as parameters and use them internally to accomplish different behaviors. Behavior parameterization lets you make your code more adaptive to changing requirements and saves on engineering efforts in the future.

行为参数化是一种方法,可以将多个不同的行为作为参数,并在内部使用它们来完成不同的行为。 行为参数化使您可以使代码更适应不断变化的需求,并节省将来的工程工作。

This is all about Behavior parameterization in java. I know this is not complete. I have just given introductory information and the implementation of Behavior parameterization. If you like this information please go through that and please share your knowledge and understanding through comment, suggestion.

这一切都与java中的Behavior参数化有关。 我知道这还不完整。 我刚刚给出了介绍性信息和行为参数化的实现。 如果您喜欢此信息,请仔细阅读并通过评论,建议分享您的知识和理解。

翻译自: https://medium.com/javarevisited/behavior-parameterization-in-java-741591461622

java 行为参数化

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值