空对象

转载 2018年04月17日 14:50:14

在类中的数据为对象时的时候,为了避免当对象为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确切类型的信息,用动态代理实现

空对象和空的对象

作为一门面向对象或者说基于对象的语言,必须要深刻理解javascript中对像的概念,下面就以空对象 和空的对象来展开对javascript对象的探讨。 我们说在javascript中有一种特殊的...
  • maobushigou
  • maobushigou
  • 2013-11-24 14:45:42
  • 942

java设计模式之空对象模式

一、空对象模式简介 在空对象模式中,一个空对象取代NULL对象的实例的检查。NULL对象不是检查空值,而是反映一个不做任何动作的关系。这样的NULL对象也可以在数据不可用的时候提供默认的行为。 在...
  • xiaokang123456kao
  • xiaokang123456kao
  • 2017-04-08 16:21:55
  • 522

js 判断对象为空或者不是对象的方法

在写js脚本的时候经常遇到对象为空或者不是对象的情况,出现这种情况我们可以用if去判断它,然后去执行相应的处理方法,具体判断他们的方法有以下几种:1、if   (typeOf(x)   ==   "u...
  • zhouzilong502086525
  • zhouzilong502086525
  • 2011-02-07 11:21:00
  • 5614

php生成空对象的两种方法

最基本的php中生成类,首先就要先定义类,包括成员变量和成员方法等,还要设计构造函数给成员变量赋值。 有没有一种快捷的方式,能够迅速创建出空对象,并对对象的成员变量赋值。 下面提供两种迅速...
  • yangshuolll
  • yangshuolll
  • 2017-11-02 00:22:39
  • 526

php创建空对象

在写接口的过程当中,手机端有需求说不让返回json数组,要返回一个对象。 那么我们可以怎么做呢? 其实很简单,强制转换即可。 声明空对象: $empty_object=(object)arra...
  • xingfuzhuizhuzhe
  • xingfuzhuizhuzhe
  • 2014-12-03 10:46:45
  • 1791

js判断对象是否为空对象

function isEmptyObject(obj) { for (var key in obj) { return false; } return tru...
  • John_jian_yo
  • John_jian_yo
  • 2017-07-19 10:33:09
  • 634

js如何判断对象为空对象

如果传入参数是数组的话可以使用arr.length属性判断是否为空,对于不具有这个特性的对象该如何判断是否为空呢?即如何判断不具有键值对。附上高票stackoverlow答案: http://sta...
  • u014291497
  • u014291497
  • 2016-08-09 18:12:43
  • 700

浅谈JavaScript空数组[]和空对象{}的布尔运算

空数组[]和空对象{}都是object类型: console.log(typeof []); // 控制台输出:object console.log(typeof {}); // 控制台输出:obje...
  • zhouziyu2011
  • zhouziyu2011
  • 2017-03-06 15:14:26
  • 666

js判断对象是否为空对象的几种方法

1.将json对象转化为json字符串,再判断该字符串是否为"{}" var data = {}; var b = (JSON.stringify(data) == "{}"); alert(b...
  • qq_38627581
  • qq_38627581
  • 2017-08-18 09:04:51
  • 24415

【JavaScript】 判断空对象区别于null、undefined

{}就是一个空对象,由于没有任何属性和方法,所以可以利用这一特点进行区别:12345678function isEmpty (object) { for (var i in object) { ...
  • sodino
  • sodino
  • 2016-05-12 17:42:50
  • 2097
收藏助手
不良信息举报
您举报文章:空对象
举报原因:
原因补充:

(最多只允许输入30个字)