我正在学习基本的软件设计模式.
单例类的基本实现是这样写的:
public class MyObject{
private volatile static MyObject obj;
private MyObject(){/*Do some heavy stuff here*/}
public static synchronized MyObject getInstance(){
if(obj==null)
obj=new MyObject();
return obj;
}
}
Run Code Online (Sandbox Code Playgroud)
但是因为我不知道调用同步方法可能很重.
我回来的时候我红了一本书介绍了Singleton类的这种实现:
public class MyObjectHolder {
private volatile static Supplier<MyObject> myObjectSupplier = () -> createMyObj();
//myObjectSupplier is changed on the first 'get()' call
public static MyObject getMyObject(){
return myObjectSupplier.get();
}
private static synchronized MyObject createMyObj(){
class MyObjectFactory implements Supplier<MyObject> {
private final MyObject clockTimer = new MyObject();
public MyObject get() { return …Run Code Online (Sandbox Code Playgroud) 我想要实现的目标可能毫无意义,但我想找到答案来满足我的好奇心。
我正在尝试创建一个有效的语句,该语句将基于另一个列表创建一个新列表,并在末尾添加一个新值。
我是 lambda 表达式的新手,我不确定应该使用哪种列表。
该方法看起来像这样:
private List<Integer> conjoin(List<Integer> list, Integer newValue){
return new ArrayList<Integer>(list).stream()
.map(value -> list.indexOf(value)==(list.size()-1) ?
Arrays.asList(value, newValue) :
Arrays.asList(value))
.flatMap(Collection::stream)
.collect(Collectors.toList());
}
Run Code Online (Sandbox Code Playgroud)
但更加整洁和高效。
或者是否有一个内置方法可以执行我不知道的相同操作?
我正在寻找一种如何以更自定义的方式使用地图功能的方法.如果我想要实现的功能不同,请您告诉我.
;lets say i have addOneToEach function working as bellow
(defn plusOne[singleInt]
(+ 1 singleInt))
(defn addOneToEach[intCollection] ;[1 2 3 4]
(map plusOne intCollection)) ;=>(2 3 4 5)
;But in a case I would want to customly define how much to add
(defn plusX[singleInt x]
(+ x singleInt))
(defn addXToEach[intCollection x] ;[1 2 3 4]
;how do I use plusX here inside map function?
(map (plusX ?x?) intCollection)) ;=>((+ 1 x) (+ 2 x) (+ 3 x) (+ 4 x)) …Run Code Online (Sandbox Code Playgroud)