SKY外语计算机学习
标题:
23种设计模式----(*独一无二*单例模式)
[打印本页]
作者:
liugenhua189
时间:
2013-6-4 20:07
标题:
23种设计模式----(*独一无二*单例模式)
本帖最后由 sky_yx 于 2015-12-30 14:09 编辑
以写日志为例:
示例代码------------------------------------------------------------------------------------
package com.moshi.singleton;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
public class logmagage {
private static PrintWriter out;
private final static String filename="G://log.txt";//设置日志问题路径
//唯一实例 logmagage
private static logmagage logmagage;
private logmagage(){
outinit();
}
public static void outinit(){
if(out==null){
try {
out=new PrintWriter(new FileWriter(filename,true),true);
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.print("无法打开日志文件");
e.printStackTrace();
out=null;
}
}
}
public static synchronized void log(String msg){
if(logmagage==null||out==null){logmagage=new logmagage();}
if(out!=null){
out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+":"+msg);
}
}
public static void destory(){
if(out!=null)out.close();
}
}
//客户端调用
package com.moshi.singleton;
public class logclient {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
logmagage.log("javaweb程序设计");//写入日志
}
}
欢迎光临 SKY外语计算机学习 (http://skywj.com/)
Powered by Discuz! X2.5