策略模式的案例

1.定义接口

策略模式 | 菜鸟教程策略模式 在策略模式(Strategy Pattern)中,一个类的行为或其算法可以在运行时更改。这种类型的设计模式属于行为型模式。 在策略模式中,我们创建表示各种策略的对象和一个行为随着策略对象改变而改变的 context 对象。策略对象改变 context 对象的执行算法。 介绍 意图:定义一系列的算法,把它们一个个封装起来, 并且使它们可相互替换。 主要解决:在有多种算法相似的情况下,使用 if...else 所带来的复杂和难..https://www.runoob.com/design-pattern/strategy-pattern.html

@FunctionalInterface
public interface MyPredicate<T> {

	public boolean test(T t);
	
}

2.实现接口

2.1 FilterEmployeeForAge

package decoration;

public class FilterEmployeeForAge implements MyPredicate<Employee>{

	@Override
	public boolean test(Employee t) {
		System.out.println("age...");
		return t.getAge() <= 35;
	}

}

2.2  FilterEmployeeForSalary

package decoration;

public class FilterEmployeeForSalary implements MyPredicate<Employee> {

	@Override
	public boolean test(Employee t) {
		System.out.println("salary...");
		return t.getSalary() >= 5000;
	}

}

2.3 实体类

package decoration;

public class Employee {

	private int id;
	private String name;
	private int age;
	private double salary;

	public Employee() {
	}

	public Employee(String name) {
		this.name = name;
	}

	public Employee(String name, int age) {
		this.name = name;
		this.age = age;
	}

	public Employee(int id, String name, int age, double salary) {
		this.id = id;
		this.name = name;
		this.age = age;
		this.salary = salary;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public double getSalary() {
		return salary;
	}

	public void setSalary(double salary) {
		this.salary = salary;
	}

	public String show() {
		return "测试方法引用!";
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + age;
		result = prime * result + id;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		long temp;
		temp = Double.doubleToLongBits(salary);
		result = prime * result + (int) (temp ^ (temp >>> 32));
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Employee other = (Employee) obj;
		if (age != other.age)
			return false;
		if (id != other.id)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		if (Double.doubleToLongBits(salary) != Double.doubleToLongBits(other.salary))
			return false;
		return true;
	}

	@Override
	public String toString() {
		return "Employee [id=" + id + ", name=" + name + ", age=" + age + ", salary=" + salary + "]";
	}

}

2.4 对外提供类

package decoration;

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

/**
 * @ClassName: Context
 * @Description: TODO
 * @Author: liujianfu
 * @Date: 2021/10/31 21:27:00 
 * @Version: V1.0
 **/
public class Context {
    private MyPredicate myPredicate;

    public Context(MyPredicate myPredicate) {
        this.myPredicate = myPredicate;
    }

    public Context() {
    }
    /**
    * @author liujianfu
    * @description      判断是否满足逻辑
    * @date 2021/10/31 21:28
    * @param [emps, mp]
    * @return java.util.List<decoration.Employee>
    */
    public List<Employee> filterEmployee(List<Employee> emps, MyPredicate<Employee> mp){
        List<Employee> list = new ArrayList<>();
        for (Employee employee : emps) {
            if(mp.test(employee)){
                list.add(employee);
            }
        }

        return list;
    }
}

2.5 测试

package decoration;

import java.util.Arrays;
import java.util.List;

/**
 * @ClassName: TestD
 * @Description: TODO
 * @Author: liujianfu
 * @Date: 2021/10/31 21:25:48 
 * @Version: V1.0
 **/
public class TestD {
    public static void main(String[] args) {
        List<Employee> emps = Arrays.asList(
                new Employee(101, "张三", 18, 9999.99),
                new Employee(102, "李四", 59, 6666.66),
                new Employee(103, "王五", 28, 3333.33),
                new Employee(104, "赵六", 8, 7777.77),
                new Employee(105, "田七", 38, 5555.55)
        );

       Context  context=new Context();

        List<Employee> ageList=  context.filterEmployee(emps,new FilterEmployeeForAge());
        for(Employee employee:ageList){
            System.out.println("employee:"+employee.getName()+" age:"+employee.getAge());
        }
       System.out.println("========================");
        List<Employee> salaryList=  context.filterEmployee(emps,new FilterEmployeeForSalary());
        for(Employee employee:salaryList){
            System.out.println("employee:"+employee.getName()+" age:"+employee.getAge()+"salary:"+employee.getSalary());
        }

        System.out.println("====");
      //使用lamda表达式
        List<Employee> list =context. filterEmployee(emps, (e) -> e.getAge() <= 35);
        list.forEach(System.out::println);

        System.out.println("------------------------------------------");

        List<Employee> list2 = context. filterEmployee(emps, (e) -> e.getSalary() >= 5000);
        list2.forEach(System.out::println);

    }
}

结果:

age...
age...
age...
age...
age...
employee:张三 age:18
employee:王五 age:28
employee:赵六 age:8
========================
salary...
salary...
salary...
salary...
salary...
employee:张三 age:18salary:9999.99
employee:李四 age:59salary:6666.66
employee:赵六 age:8salary:7777.77
employee:田七 age:38salary:5555.55
====
Employee [id=101, name=张三, age=18, salary=9999.99]
Employee [id=103, name=王五, age=28, salary=3333.33]
Employee [id=104, name=赵六, age=8, salary=7777.77]
------------------------------------------
Employee [id=101, name=张三, age=18, salary=9999.99]
Employee [id=102, name=李四, age=59, salary=6666.66]
Employee [id=104, name=赵六, age=8, salary=7777.77]
Employee [id=105, name=田七, age=38, salary=5555.55]

Process finished with exit code 0
 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值