一.在函数中不要出现常量,可采用定义静态成员常量的方式.
private static final int NUM = 5;
for(int i=0;i<NUM,i++){
........
}
二.设计模式的使用:
使用的是其思想,不拘泥于具体的代码实现形式.
1.工厂模式:
public static Object newInstance(){
return new Object();
}
2.单例模式:
1)饿汉式单例模式:
private static final ArrayList arraylist = new ArrayList();
2)懒汉式单例模式:
class SingleInstance{
private static SingleInstance obj;
private SingleInstance(){};
public static SingleInstance getInstance(){
if(obj == null){
obj = new SingleInstance();
}
return obj;
}
}
3)DCL(Double-Checked-Lock)单例模式:
class DclInstance{
private DclInstance(){};
private static DclInstance obj;
public static DclInstance getInstance(){
if( obj == null){
synchronized(DclInstance.Class){
if(obj == null){
obj = new DclInstance();
}
}
}
}
}
3.代理模式:
JDBC中连接池使用示例:
public Connection getInstance() throws SQLException{
Connection conn = List.remove(0);//没取出一个元素,则将其从连接池中移除
return new MyConnection(conn);//利用代理模式,重写Connection类
}
public class MyConnection implements Connection{
private Connection conn;
public MyConnection(Connection conn) {
super();
this.conn = conn;
}
@Override
public void close() throws SQLException {
linkList.add(conn);
System.out.println("释放到连接池" + linkList.size());
}
@Override
..................
}
getInstance()方法中将Connection的对象conn注入到自定义的Connection子类MyConnection中,最后返回MyConnection对象.为了使连接池中的Connection保持数量固定与有效性,重写Connection类,主要目的是覆盖close()方法,其它方法暂未用到,因而沿用父类.