设计模式之-迭代器(Iterator)模式 + 建造者(Build)模式

本文介绍了设计模式中的迭代器(Iterator)模式和建造者(Builder)模式。迭代器模式提供了一种访问容器对象元素的方法而不暴露其内部结构。建造者模式则将复杂对象的构建与表示分离,使得同样的构建过程可以创建不同表示。文中通过代码示例展示了如何在Java中实现这两种模式,并强调了在实际应用中应根据需求灵活运用设计模式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

迭代器(Iterator)模式

又叫做游标(Cursor)模式。GOF给出的定义为:提供一种方法访问一个容器(container)对象中各个元素,而又不需暴露该对象的内部细节。 从定义可见,迭代器模式是为容器而生。很明显,对容器对象的访问必然涉及到遍历算法。你可以一股脑的将遍历方法塞到容器对象中去;或者根本不去提供什么遍历算法,让使用容器的人自己去实现去吧。这两种情况好像都能够解决问题。

建造者(Build)模式

将一个复杂对象的构造与它的表示分离,使同样的构建过程可以创建不同的表示,这样的设计模式被称为建造者模式

满足原则:

单一原则
开闭原则
迭代器模式和建造者模式是非常简单的模式,下面直接上代码。

建立一个实体对象

package Iterator.normal;

/**
 * 
 * @author Allen 
 * @date 2017年2月15日
 *
 */
public class UserVo {
   
   

    private final int u_id;// id
    private final String u_name;// 名称
    private final int u_age;// 年龄

    private UserVo(int u_id, String u_name, int u_age) {
        super();
        this.u_id = u_id;
        this.u_name = u_name;
        this.u_age = u_age;
    }

    public int getU_id() {
        return u_id;
    }

    public String getU_name() {
        return u_name;
    }

    public int getU_age() {
        return u_age;
    }
    /**
     * 建造者模式
     * @author Allen 
     * @date 2017年2月15日
     *
     */
    public static class UserBuild {
   
   
        private int u_id;// id
        private String u_name;// 名称
        private int u_age;// 年龄

        public UserBuild() {
            // TODO Auto-generated constructor stub
        }

        public UserBuild u_id(int u_id) {
            this.u_id = u_id;
            return this;
        }

        public UserBuild u_name(String u_name) {
            this.u_name = u_name;
            return this;
        }

        public UserBuild u_age(int u_age) {
            this.u_age = u_age;
            return this;
        }

        public UserVo build() {
            return new UserVo(u_id, u_name, u_age);
        }
    }

    public static UserBuild 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值