zoukankan      html  css  js  c++  java
  • Java编程设计2

    一般我们会以这种设计方式生产对象实例,如:

    创建一个接口:

    public interface TestOpen {
    
        String getVirtualHost();
    
        String getCapabilities();
    
        boolean getInsist();
    
    }

    实现该接口:

    public class TestOpenImpl implements TestOpen {
    
        private String t1;
        private String t2;
        private String t3;
        public TestOpenImpl()
        {
    
        }
        public TestOpenImpl(String t1,String t2,String t3)
        {
            //doSomething...
        }
        @Override
        public String getVirtualHost() {
            return null;
        }
    
        @Override
        public String getCapabilities() {
            return null;
        }
    
        @Override
        public boolean getInsist() {
            return false;
        }
    }

    创建一个构造器:

    public class TestOpenBuilder {
        public static  TestOpen Build()
        {
            return new TestOpenImpl();
        }
        public static  TestOpen Build(String t1,String t2,String t3)
        {
            return new TestOpenImpl(t1,t2,t3);
        }
    }

    所以在构造实例对象时,需要:

    TestOpenBuilder.Build()或TestOpenBuilder.Build("","","");

    如果将构造器封装在interface中,如这样所示:

    public interface TestOpen {
    
        String getVirtualHost();
    
        String getCapabilities();
    
        boolean getInsist();
    
        final class Build
        {
            private   String t1;
            private String t2;
            private String t3;
            public   TestOpen.Build t1(String t1){
    
                this.t1=t1;
                return this;
            }
            public TestOpen.Build t2(String t2){
    
                this.t2=t1;
                return this;
            }
            public TestOpen.Build t3(String t3){
    
                this.t3=t3;
                return this;
            }
            public TestOpen build()
            {
                return new TestOpenImpl(this.t1,this.t2,this.t3);
            }
        }
    
    }

    则我们在构造时,可以这样:

    TestOpen testOpen = new TestOpen.Build().t1("haha").t2("21").t3("23").build();

    这样做的好处:可以将接口与其构建器关联起来,方便使用。
  • 相关阅读:
    Java中的equals方法和==的区别
    C语言学习笔记--单向链表Markdown版本
    Tamias Blog's
    nginx图片服务器
    Nginx安装解决报错
    Detour框架注入样本无法正常启动(0x000007b)
    结构体指针中包含结构体指针
    Linux开发准备:Ubuntu14.04+Samba+MobaXterm+Source Insight 4.0
    在Visual Studio中将dll以资源的形式嵌入exe中
    MACD的价值不在于“金叉死叉”而在于背离
  • 原文地址:https://www.cnblogs.com/itdev/p/5666627.html
Copyright © 2011-2022 走看看