Design Mode: Null Object Mode

Source: Internet
Author: User

The null object is referenced to cancel Null Object judgment in business logic.


Class diagram:




Nullable:

package com.demo.user;public interface Nullable {boolean isNull();}


GROUP:

package com.demo.user;public class Group implements Nullable{private int groupId;private String groupName;public int getGroupId() {return groupId;}public void setGroupId(int groupId) {this.groupId = groupId;}public String getGroupName() {return groupName;}public void setGroupName(String groupName) {this.groupName = groupName;}public boolean isNull() {return true;}}


Nullgroup:

package com.demo.user;public class NullGroup extends Group {private NullGroup() {}@Overridepublic int getGroupId() {return 9999999;}@Overridepublic boolean isNull() {return false;}static Group createNull(){return new NullGroup();}}


User:

Package COM. demo. user; public class user {private int userid; private string username; private group; Public int getuserid () {return userid;} public void setuserid (INT userid) {This. userid = userid;} Public String GetUserName () {return username;} public void setusername (string username) {This. username = username;} public group getgroup () {// returns an nullgroup object return group = NULL? Nullgroup. createnull (): group;} public void setgroup (group Group) {This. Group = group ;}}


Userservice:

Package COM. demo. user; public class userservice {public void add (User user) {// obtain groupidint groupid = user. getgroup (). getgroupid (); // doing something }}





Design Mode: Null Object Mode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.