如何在Clojure中使用构建器模式创建类似Java的对象? [英] How do I create a Java-like object in Clojure that uses builder pattern?

查看:134
本文介绍了如何在Clojure中使用构建器模式创建类似Java的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Clojure,如何创建以下对象?对象取自Java代码(From Effective Java):



NutritionFacts cocaCola =
new NutritionFacts.Builder(240,8).calories(100).sodium(35).carbohydrate(27).build();

1 , .. 有些失去了偏爱,被更多样化的 - > 所取代。个人我更喜欢:

 ( - > NutritionFacts $ Builder。240 8)
(.calories 100)
(.sodium 350)
(.carbohydrates 27)
(.build))

这是多了几个字符,但你有两件事:




  • 显性。我可以看看钠行(例如),并告诉它是一个Java方法调用,因为就在那里。

  • 灵活性。如果我需要,我可以在中间链接一些非方法调用(打印到stdout,说),或者在所有这些的结尾进入一些其他函数调用。



最重要的是,这个问题的所有其他答案都得到了错误的类名:Java的NutritionFacts.Builder是一个名为NutritionFacts $ Builder的实际JVM类的语言糖,是Clojure必须引用的(因为我们没有使用javac来编译我们的代码)。



1 我不同意< c $ c> doto 建议:它的工作原理只是因为这个Builder类碰巧通过突变单个实例然后返回它实现它的方法链。 doto 是伟大的Java对象,需要原地的突变,但当一个类是足够的,假装它是不可变的,你应该真正使用方法链的版本(即, - > )。


Using Clojure, how do I create the following object? The object is taken from java code (From Effective Java):

NutritionFacts cocaCola = new NutritionFacts.Builder(240,8).calories(100).sodium(35).carbohydrate(27).build();

解决方案

While it's hard to argue with the concision in the other answers1, .. has somewhat fallen out of favor, replaced by the more versatile ->. Personally I prefer :

(-> (NutritionFacts$Builder. 240 8) 
    (.calories 100)
    (.sodium 350)  
    (.carbohydrates 27) 
    (.build))

It's a couple more characters, but you gain two things:

  • Explicitness. I can look at the sodium line (for example) and tell it's a Java method call, because the . is right there.
  • Flexibility. If I need to, I can chain some non-method call in the middle there (printing it to stdout, say), or at the end of all this feed it in to some other function call.

Most importantly, every other answer to this question has gotten the classname wrong: Java's NutritionFacts.Builder is language sugar over the real JVM class named NutritionFacts$Builder, and that class is the one Clojure must refer to (since we are not using javac to compile our code).

1 I do disagree with the doto suggestion: it works only because this Builder class happens to implement its method-chaining by mutating a single instance and then returning it. doto is great for Java objects that require in-place mutation, but when a class is kind enough to pretend it's immutable you should really be using the method-chaining version (ie, ->).

这篇关于如何在Clojure中使用构建器模式创建类似Java的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆