空对象

在类中的数据为对象时的时候,为了避免当对象为null时误用它,在利用它之前都应该检查是否为null

 在一些情况下,我们可以用空对象去代替

让我们看一下Person和职位的匹配关系

先用内部类去实现

//标记接口
interface Null{}

class Person{
    public final String first;
    public final String last;
    public final String address;

    public Person(String first, String last, String address){
        this.first = first;
        this.last = last;
        this.address = address;
    }

    public String toString(){
        return "Person: " + first + " " + last + " " + address;
    }

    public static class NullPerson extends Person implements Null{     // 空的Person
        private NullPerson(){ super("None", "None" , "None");}
        public String toString(){ return "NullPerson"; }
    }
    public static final Person NULL = new NullPerson();
}

class Position{
    private String title;
    private Person person;
    public Position(String jobTitle, Person employee){              

        title = jobTitle;
        person = employee;
        if(person == null){
            person = Person.NULL;
        }
    }

    public Position(String jobTitle){
        title = jobTitle;
        person = Person.NULL;
    }

    public String getTitle(){
        return title;
    }

    public void  setTitle(String newTitle){
        title = newTitle;
    }

    public Person getPerson(){
        return person;
    }

    public void setPerson(Person newPerson){
        person = newPerson;
        if(person == null){
            person = Person.NULL;
        }
    }

    public String toString(){
        return "Position: " + title + " " + person;
    }
}

class Staff extends ArrayList<Position>{
    public void add(String title, Person person){
        add(new Position(title, person));
    }

    public void add(String... titles){
        for(String title : titles){
            add(new Position(title));
        }
    }

    public Staff(String... titles){
        add(titles);
    }

    public boolean positionAvailable(String title){
        for(Position position : this ){
            if(position.getTitle().equals(title) && position.getPerson() == Person.NULL)
            {
                return true;
            }
        }
        return false;
    }

    public void fillPositon(String title, Person hire){
        for(Position position : this){
            if(position.getTitle().equals(title) && position.getPerson() == Person.NULL){
                position.setPerson(hire);
                return;
            }
        }
        throw new RuntimeException("Position " + title
        + " not available");
    }
}

public class Main{

    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        Staff staff = new Staff("President","CTO",
                "Marketing Manager", "Product Manager",
                "Project lead", "Software Engineer",
                "Software Engineer", "Software Engineer",
                "Software Engineer", "Test Engineer",
                "Technical Writer");
        staff.fillPositon("President", new Person("ME", "Last", "the top , lonely At"));
        staff.fillPositon("Project lead", new Person("Janet", "Planner", "the burbs"));
        if(staff.positionAvailable("Software Engineer")){
            staff.fillPositon("Software Engineer", new Person("Bob", "coder", "bright light city"));
        }
        System.out.println(staff);
    }
}

运行结果:

[Position: President Person: ME Last the top , lonely At, 

Position: CTO NullPerson, 

Position: Marketing Manager NullPerson, 

Position: Product Manager NullPerson, 

Position: Project lead Person: Janet Planner the burbs, 

Position: Software Engineer Person: Bob coder bright light city, 

Position: Software Engineer NullPerson, 

Position: Software Engineer NullPerson, 

Position: Software Engineer NullPerson, 

Position: Test Engineer NullPerson, 

Position: Technical Writer NullPerson]

  来看个“机器人”例子,代理模式

interface Null{}

interface Operation{
    String description();
    void command();
}

interface Robot{
    String name();
    String model();
    List<Operation> operations();
    class Test{
        public static void test(Robot r){
            if(r instanceof Null)
                System.out.println("[Null Robot]");
            System.out.println("Robot name: " + r.name());
            System.out.println("Robot model: " + r.model());
            for(Operation operation : r.operations()){
                System.out.println(operation.description());
                operation.command();
            }
        }
    }
}

class SnowRemovalRobot implements Robot{
    private String name;
    public SnowRemovalRobot(String name) {
        this.name = name;
    }
    public String name() { return name;}
    public String model() { return "Snow Series 11" ;}
    public List<Operation> operations(){
        return Arrays.asList(
                new Operation() {
                    @Override
                    public String description() {
                        return name + " can shovel snow";
                    }

                    @Override
                    public void command() {
                        System.out.println(name + " shoveling snow");
                    }
                },
                new Operation() {
                    @Override
                    public String description() {
                        return name + " can chip ice";
                    }

                    @Override
                    public void command() {
                        System.out.println(name + " shoveling snow");
                    }
                },
                new Operation() {
                    @Override
                    public String description() {
                        return name + " can clear the roof";
                    }

                    @Override
                    public void command() {
                        System.out.println(name + " clearing roof");
                    }
                }
        );
    }
}

public class Main{

    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        Robot.Test.test(new SnowRemovalRobot("Slusher"));
    }
}

运行结果:

Robot name: Slusher
Robot model: Snow Series 11
Slusher can shovel snow
Slusher shoveling snow
Slusher can chip ice
Slusher shoveling snow
Slusher can clear the roof

Slusher clearing roof

  如果存在许多不同类型的Robot,我们想对每一种Robot类型都创建一个空对象,去执行某种特殊操作,下面例子,提供空对象所代表的Robot确切类型的信息,用动态代理实现

阅读更多
文章标签: java
个人分类: java
上一篇代理模式
下一篇利用反射来向下转型
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭