后续我会陆陆续续更新《ava程序员开发手册》这一栏目的内容。大家如果觉得对自己有用就点个关注吧。
本文主要来自于《Effective Java (中文第三版)》的读后感与总结,并加上一些我自己的理解,和查阅的资料
下面先来简单看一下构造器和静态工厂方法的代码吧!
public class Test_01 {
/**
* 这是公有的有参构造器
*/
String name;
public Test_01(String name){
this.name = name;
}
/**
* 这是公有的无参构造器
*/
public Test_01(){
}
/**
* 这是一个静态工厂方法
*/
public static Test_01 getTest_01Obj(boolean check,String param){
if(check){
return new Test_01();
}else{
return new Test_01(param);
}
}
/**
* 静态工厂方法:获取一个狗的对象
*/
public static Test_01 getDog(){
return new Test_01("Dog");
}
/**
* 静态工厂方法:获取一个空的对象
*/
public static Test_01 getNull(){
return new Test_01();
}
}
这种静态工厂方法和设计模式中的静态工厂方法是不的,请不要混在一起,可以理解为构造器的封装。
/**
* 静态工厂方法:获取一个狗的对象
*/
public static Test_01 getDog(){
return new Test_01("Dog");
}
/**
* 静态工厂方法:获取一个空的对象
*/
public static Test_01 getNull(){
return new Test_01();
}
上面举了一个比较简单的例子,参数很短,逻辑也很简单,但也能体现出你在代码中如果写getDog总比new Test_01("Dog")更明确。
public class Singleton {
private static Singleton singleton;
private Singleton(){
System.out.println("我是一个单利对象");
}
public static Singleton getSingleton(){
if(singleton == null){
singleton = new Singleton();
return singleton;
}
return singleton;
}
}
这句话就不是很好理解了,意思就是说,再返回之前某个类可能是在程序运行过程中自动生成的,并且返回给你。和动态代理的实现是一个事情。