1206yaya
6/13/2015 - 11:01 PM

継承とインターフェースの使い方 複数レベルのポリモーフィズム

継承とインターフェースの使い方 複数レベルのポリモーフィズム


public class 複数レベルのポリモーフィズム {
}

interface Employee {
	public String getName();

	public float getSalary();

	public float calcAnnualBouns();

	public int getDaysOffSick();
}

abstract class AbstractEmployee implements Employee {
	private String name_;
	private float salary_;
	private int sickdays_;

	public AbstractEmployee(String name_, float salary_, int sickdays_) {
		this.name_ = name_;
		this.salary_ = salary_;
		this.sickdays_ = sickdays_;
	}

	public String getName() {
		return name_;
	}

	public float getSalary() {
		return salary_;
	}

	public int getDaysOffSick() {
		return sickdays_;
	}
}

class FatCatEmployee extends AbstractEmployee {
	public FatCatEmployee(String name_, float salary_, int sickdays_) {
		super(name_, salary_, sickdays_);
	}

	@Override
	public float calcAnnualBouns() {
		float loadsOfMoney = 0F;
		System.out.println("FatCatEmployee.calcBouns");
		return loadsOfMoney;
	}
}

class LowPaidEmployee extends AbstractEmployee {
	public LowPaidEmployee(String name_, float salary_, int sickdays_) {
		super(name_, salary_, sickdays_);
	}

	@Override
	public float calcAnnualBouns() {
		System.out.println("LowPaidEmployee.calcBouns");
		return 0F;
	}

}
interface PayModel { // 新たに追加されたinterface
	public float calcEmployeeCost(Employee emp);
}

final class IncentivePayModel implements PayModel {
	@Override
	public float calcEmployeeCost(Employee emp) {
		// このモデルでは病欠日数によってボーナスを変える
		// 病欠が5日より少ない場合には10%上乗せする
		float sal = emp.getSalary();
		float bonus = emp.calcAnnualBouns();
		int sick_days = emp.getDaysOffSick();
		float total_cost = sal;
		if (sick_days < 5) {
			total_cost += (bonus * 1.1);
		} else if (sick_days > 10) {
			total_cost += (bonus * 0.9);
		}
		return total_cost;
	}
}

final class SimplePayModel implements PayModel {
	@Override
	public float calcEmployeeCost(Employee emp) {
		// このモデルではボーナス計算を行わず給与を15%増やす
		return emp.getSalary() * 1.15F;
	}
}

final class EmployeeOperations {
	public static float calcCostOfEmployees(Iterator employees,
			PayModel pay_model) {
		float total_cost = 0F;
		while (employees.hasNext()) {
			Employee emp = (Employee) employees.next();
			total_cost += pay_model.calcEmployeeCost(emp);
		}
		return total_cost;
	}

	public static void main(String[] args) {
		List<Employee> emps = new ArrayList<>();
		emps.add(new FatCatEmployee("Boss", 500000, 20));
		emps.add(new LowPaidEmployee("Tea Boy", 5000, 1));
		Iterator<Employee> it = emps.iterator();
		PayModel pm1 = new SimplePayModel();
		PayModel pm2 = new IncentivePayModel();
		float cost1 = EmployeeOperations.calcCostOfEmployees(it, pm1);
		float cost2 = EmployeeOperations.calcCostOfEmployees(it, pm2);
		System.out.println("SimplePayModel costs = " + cost1);
		System.out.println("IncentivePayModel costs = " + cost2);
	}
}