单例设计模式:
私有化类的构造函数,使外部不能直接创建对象,由类内部静态方法返回一个自身对象,以保证对象的唯一性。
单例设计模式的两种方式:
饿汉式:
class Single {
private static Single instance = new Single();
private Single(){}
public static Single getInstance(){
return instance;
}
}
懒汉式:
class Single {
private static Single instance = new Single();
private Single(){}
public static Single getInstance(){
if (null == instance) {
synchronized (Single.class) {
if (null == instance) {
instance = new Single();
}
}
}
return instance;
}
}
实际开发中一般使用饿汉式,因为懒汉式须要处理线程同步问题。但个人认为当不确定类Single的对象在程序中是否一定被使用且对象较大时,最好使用懒汉式,以便节约内存。
模板方法设计模式:
某一函数的部分功能是确定的,另一部分是不确定的。将确定的部分封装成一个不可被复写的函数,如final修饰 .将不确定的部分用另一个函数抽取出来暴露给子类去复写,然后由前者调用后者。
abstract class getRunTime {
abstract void runCode();
public final long runTime(){
long time = System.currentTimeMillis();
runCode();
time = System.currentTimeMillis() - time;
return time;
}
}
class Demo {
public static void main(String[] args) {
long time = new getRunTime(){
@Override
void runCode() {
// 这里添加须要测试的运行时间代码,
// 然后在调用代码块中建立getRunTime对象,并调用runTime方法
for (int i = 0; i < 1000; i++) {
System.out.println(i);
}
}
}.runTime();
System.out.println(time);
}
}
装饰设计模式:
将原有功能对象通过构造函数传入新的封装类的对象中并在内部对功能增强,向外部提供增强后的使用方法,以达到原有功能增加的效果,称之为装饰设计模式,也可以称为包装类。
//第三方类
interface ThirdParty {
public String msg();
}
//装饰者继承第三方类
class Decorator implements ThirdParty {
//被装饰的对象引用
private ThirdParty thirdParty;
//构造的同时传递进来被装饰对象
public Decorator(ThirdParty thirdParty){
this.thirdParty= thirdParty;
}
//覆盖原第三方功能,返回被装饰对象功能
@Override
public String msg() {
return thirdParty.msg();
}
//对被装饰功能加强后向外提供
public String strengthenSay(){
return "Strengthen:" + msg() ;
}
}
享元设计模式:
当一个类的对象有大量实例时,发现这些实例之间存在着共同性,将共同性一样的对象抽离,使用同一个实体共享给这些实例可以较好的节约内存。
在Java中这一思想被重点规划,因为C++中存在着栈中对象的创建,以及对象复制传递等特性,C++中的享元模式被强调于复制构造函数的使用频率与时机所覆盖。其实也就是相同元素共享同一块内存空间,在Java中这一理念被强调性的提出并规划出相应原设计模式。
享元模式通过共享对象节省总体资源,共享对象将导致资源访问上的一些缺憾,包括对象实例的回收,包括线程间的共享。一般线程退出的时候,会自动释放线程内部的申请的资源,但是对于线程间共享的对象也许不会自动回收,这些工作需要调用进程来进行。
//字体类型基类
class FontBase {
//字体类型集合
private List<String> font = new LinkedList<String>();
//字体类型名字
private String fontName;
//构造一个字体类型
public FontBase(String name) {
this.fontName = name;
}
//为新字体类型添加字体元素
public FontBase AddFont(String font) {
this.font.add(font);
return this;
}
//获取字体类型的名字
public String getFontName(){
return this.fontName;
}
}
//新的字体
class ChineseFont extends FontBase {
public ChineseFont() {
super("ChineseFont");
super.AddFont("ChineseFont");
}
}
//新的字体
class EnglishFont extends FontBase {
public EnglishFont() {
super("EnglishFont");
super.AddFont("EnglishFont");
}
}