设计模式
设计模式有23种
单例设计模式
它又分为“饿汉设计模式”和“懒汉设计模式”
饿汉设计模式在线程上安全,但占用资源。
懒汉设计模式在线程上不安全。
public class Demo5{
public static void main(String[] args) {
Single2 s = Single2.getInstance();
Single2 s1 = Single2.getInstance();
System.out.println(s==s1);
}
}
/**饿汉单例设计模式*/
class Single1 {
private static Single1 s = new Single1();
private Single1() {
}
public static Single1 getInstance() {
return s;
}
}
/**懒汉单例设计模式*/
class Single2{
private static Single2 s;
private Single2() {
}
public static Single2 getInstance() {
if (s==null) {
s = new Single2();
}
return s;
}
}
简单工厂设计模式
1、工厂类(一般把方法定义成静态的,方便用户调用)
2、抽象类。接口(与客户交互)
3、具体产品类
4、客户(调用工厂类)
简单工厂模式的延伸–抽象工厂模式。
public class Factory { // 商品工厂
/**选择商品*/
public static Goods getGoods(String type) {
Goods goods = null;
if (type.equals("TV")) {
goods = new Tvs();
}else {
goods = new Foods();
}
return goods;
}
}
/**抽象类*/
public abstract class Goods {
public abstract void buy();
}
/**具体产品类*/
class Foods extends Goods {
@Override
public void buy() {
System.out.println("鱼罐头");
}
}
public class Tvs extends Goods {
@Override
public void buy() {
System.out.println("海尔电视");
}
}
/**客户类*/
public class Test {
public static void main(String[] args) {
Goods goods = Factory.getGoods("TV");
goods.buy();
}
}