栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

OO设计建议-toString

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

OO设计建议-toString

所有这些方法均已使用,并且无法提供“与上下文无关”的最佳实践。软件工程中最好的答案通常是“取决于情况”。就是说,让我们分析一下每个:

  1. 最好的KISS方法。我用我所有的基本“打印到控制台,确保一切正常”的方式执行此操作。如果您希望使用特定格式的地址,那么这是低挂的水果/轻松获胜解决方案。您始终可以覆盖此设置,或者在一种情况下以不同方式打印对象。
  2. 这是最可扩展的解决方案,因为它将很好地支持本地化和自定义格式。是否合适取决于您期望地址以不同格式显示的频率。您是否真的需要那颗死亡之星来击败苍蝇,或者是否能够将所有大写字母或两种语言之间的转换对您的应用程序至关重要?
  3. 我不建议采用这种方法,因为它通常开始将“视图级别”逻辑渗入到Domain中,通常最好由其他层(在类MVC方法中)来处理。有人可能会说toString()做相同的事情,但是toString()也可以被认为是对象在外部世界中的外观的“名称”或“本质”,所以我要说的不仅仅是表象。 。

希望这对您有所帮助,并从一开始就对“干净代码”,“解耦”和“可维护性”进行思考。

对于行动中的原则2的示例-使用策略模式,遵循单一职责原则,开放/封闭原则并允许通过依赖注入进行控制反转
-比较以下方法(@SteveJ慷慨提供) :

public class Address {        private String streetAddress;        private int number;        private String postalCode;        private String city;        private String state;        private String country;        public String toLongFormat(){ return null; // stitch together your long format        }        public String toShortFormat(){ return null; // stitch together your short format        }        public String toMailingLabelFormat(){ return null; // stitch together your mailing label format        }        @Override        public String toString(){ return toShortFormat(); // your default format        }    }}

有了这个(在“最正确的” Groovy中):

public interface AddressFormatter {   String format(Address toFormat)}public class LongAddressFormatter implements AddressFormatter {    @Override    public String format(Address toFormat){         return String.format("%sBLAHBLAHBLAHBLAHBLAHBLAHBLAHBLAHBLAHBLAHBLAHBLAHBLAHBLAHBLAHBLAHBLAH%n%s", toFormat.streetAddress, toFormat.postalCode)    }}public class ShortAddressFormatter implements AddressFormatter {    @Override    public String format(Address toFormat){         return String.format("%d", toFormat.number)    }}public  class Address {        private String streetAddress;        private int number;        private String postalCode;        private String city;        private String state;        private String country;        public  AddressFormatter formatter = new ShortAddressFormatter(); // just to avoid NPE        public void setFormatter(AddressFormatter fr) { this.formatter = fr; }        @Override        public String toString(){ return formatter.format(this); // your default format        }    }def addrr = new Address(streetAddress:"1234 fun drive", postalCode:"11223", number:1)addr.setFormatter(new LongAddressFormatter());println "The address is ${addrr}"addr.setFormatter(new ShortAddressFormatter());println "The address is ${addrr}"

正如@SteveJ观察到的:

“因此,您有不同的格式化“策略”,您可以在它们之间进行切换…我有个想法,您将设置一次格式化并坚持下去…并且如果您想添加其他格式化样式,则不要不必打开并重写地址类,而可以编写新的单独样式并在需要使用时注入它。”



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/483658.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号