Java常用的设计模式
单例模式:
恶汉模式:
public class SingleTonHungry {
private static SingleTonHungry singleTonHungry = new SingleTonHungry();
private SingleTonHungry() {
}
public static SingleTonHungry getInstance() {
return singleTonHungry;
}
}
懒汉模式:线程安全的懒汉模式
public class SingleTonLazy {
private static SingleTonLazy singleTonLazy = null;
private SingleTonLazy() {
}
public static SingleTonLazy getInstance() {
if (singleTonLazy == null) {
synchronized (SingleTonLazy.class) {
if (singleTonLazy == null) {
singleTonLazy = new SingleTonLazy();
}
}
}
return singleTonLazy;
}
}
抽象工厂模式:
抽象工厂
public interface PhoneFactory {
Phone producePhone();
}
具体对象工厂
public class IPhoneFactory implements PhoneFactory {
@Override
public Phone producePhone() {
return new IPhone();
}
}
public class XiaomiFactory implements PhoneFactory{
@Override
public Phone producePhone() {
return new Xiaomi();
}
}
接口
public interface Phone {
void call();
}
具体对象
public class IPhone implements Phone{
@Override
public void call() {
System.out.println("this is iphone");
}
}
public class Xiaomi implements Phone{
@Override
public void call() {
System.out.println("this is xiaomi");
}
}
测试
public class FactoryTest {
public static void main(String[] args) {
PhoneFactory producePhone = new IPhoneFactory();
Phone p = producePhone.producePhone();
p.call();
producePhone = new XiaomiFactory();
Phone xiaomi = producePhone.producePhone();
xiaomi.call();
}
}