谷歌面试题:继承关系变组合关系

题目描述

一个项目中有Employee类型,该类型是个大类型,下分为Engineer类型和Manager类型。比方一个人开始是Engineer类型,后来升职了,变成了Manager的角色,这种情况,应该如何建模更好一些。

思路

变继承关系为组成关系,方便扩展。

代码

定义一个Role的接口:

public interface Role {
    void doWork();
}

 

定义Employee类型:

public class Employee {
    private final String name;
    private final int salary;
    private Role role;

    public Employee(String name, int salary, Role role) {
        this.name = name;
        this.salary = salary;
        this.role = role;
    }

    public String getName() {
        return name;
    }

    public int getSalary() {
        return salary;
    }

    public Role getRole() {
        return role;
    }

    public void setRole(Role role) {
        this.role = role;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", salary=" + salary +
                ", role=" + role +
                '}';
    }

    public void doWork(){
        this.role.doWork();
    }
}

 

定义Engineer类型:

public class Engineer implements Role {
    @Override
    public void doWork() {
        System.out.println("Doing Engineer work.");
    }

    @Override
    public String toString() {
        return "Engineer";
    }
}

 

定义Manager类型:

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

public class Manager implements Role {
    private List<Employee> reporters;

    public Manager(List<Employee> reporters) {
        this.reporters = new ArrayList<>(reporters);
    }

    @Override
    public void doWork() {
        System.out.println("Dispatching work.");
        Employee employee = selectReporter();
        employee.doWork();
    }

    private Employee selectReporter() {
        return reporters.get(0);
    }

    @Override
    public String toString() {
        return "Manager";
    }
}

 

最后进行测试,将“陈驰”的角色由Engineer变成Manager :

import java.util.Arrays;

public class Test {
    public static void main(String[] args) {
        Employee employee1 = new Employee("陈驰", 20000, new Engineer());
        Employee employee2 = new Employee("魏印福", 20000, new Engineer());

        System.out.println(employee1);
        System.out.println(employee2);

        System.out.println("Employee1:");
        employee1.doWork();
        System.out.println("Employee2:");
        employee2.doWork();

        System.out.println("职位升迁......");

        employee1.setRole(new Manager(Arrays.asList(employee2)));
        System.out.println(employee1);
        System.out.println(employee2);

        System.out.println("Employee1:");
        employee1.doWork();
        System.out.println("Employee2:");
        employee2.doWork();
    }
}

 

查看测试结果:

 

posted @ 2019-01-31 21:07  DarrenChan陈驰  阅读(407)  评论(1编辑  收藏  举报
Live2D