Android建造者模式

来源:互联网 发布:股票资产分析软件 编辑:程序博客网 时间:2024/05/02 02:19

Android设计模式在开发中还是比较常用的,当初除了会个单例其他啥都不会。今天为了修改工具类,稍微了解了下建造者模式。
用了明了的例子就是:A.b().c()。这种情况。我们最常见的就是dialog会用到了。先上dialog的demo:

 private   void  showDialog(Context context) {          AlertDialog.Builder builder =  new  AlertDialog.Builder(context);          builder.setIcon(R.drawable.icon).setTitle( "Title" ).setMessage( "Message" ).setPositiveButton( "Button1" ,                   new  DialogInterface.OnClickListener() {                       public   void  onClick(DialogInterface dialog,  int  whichButton) {                          setTitle( "点击了对话框上的Button1" );                      }                  }).setNeutralButton( "Button2" ,                   new  DialogInterface.OnClickListener() {                       public   void  onClick(DialogInterface dialog,  int  whichButton) {                          setTitle( "点击了对话框上的Button2" );                      }                  }).setNegativeButton( "Button3" ,                   new  DialogInterface.OnClickListener() {                       public   void  onClick(DialogInterface dialog,  int  whichButton) {                          setTitle( "点击了对话框上的Button3" );                      }                  });          builder.create().show();  // 构建AlertDialog, 并且显示    } 

说白了就是一次性设置好多东西,下面我们就通过一个简单的例子来实现这样的功能。
我需要动态设置一个人的年龄,性别以及姓名。但只能在一个textview上显示。下面上代码:

public class Test {    public Set set() {        return new Set();    }    public void overload(Set set) {        set.textView.setText(set.age+":"+set.name+":"+set.value+".");    }    public class Set {        private int age;        private String name;        private String value;        private TextView textView;        public Set setAge(int age) {            this.age = age;            return this;        }        public Set setName(String name) {            this.name = name;            return this;        }        public Set setValue(String value) {            this.value = value;            return this;        }        public Set setTextView(TextView textView) {            this.textView = textView;            return this;        }        public void over() {            overload(this);        }    }}

在Test这个类通过返回一个Set对象。Set方法中,每个返回本类实例的对象。最后通过over方法来调用Test的overload方法完成设置。
调用方法:

        test=new Test();        test.set().setAge(18).setName("张三").setValue("男").setTextView(text).over();

最后上效果图:
这里写图片描述
总结:
如果类的构造器中具有多个参数,设计这种类,建造者模式就是个不错的选择,特别有很多可选参数的时候,使用传统的构造器,并没有建造者模式简单。
好了。除了单例,我又学会了建造者的使用,你们是不是也学会了呢?

1 0
原创粉丝点击