talk is cheap show me the code
单例模式
- 懒汉模式
class Singleton{
private static final Singleton instance = null;
private Singleton(){}
public static Singleton getInstance(){
if(null == instance){
instance = new Singleton();
}
return instance;
}
}
- 恶汉模式
class Singleton{
private static final Singleton instance = new Singleton;
private Singleton(){}
public static Singleton getInstance(){
if(null == instance){
instance = new Singleton();
}
return instance;
}
}
- 线程安全模式
class Singleton{
private static final Singleton instance = null;
private Singleton(){}
public static Singleton getInstance(){
if(null == instance){
synchronized(instance ){
if(null == instance){
instance = new Singleton();
}
}
}
return instance;
}
}
工厂模式
- 简单工厂模式
interface SimpleProduct{
void doSomething();
}
class ProductA extends SimpleProduct{
public void doSomething(){
system.out.println("this is Product A");
}
}
class ProductB extends SimpleProduct{
public void doSomething(){
system.out.println("this is Product B");
}
}
class SimpleFactory{
public static SimpleProduct getProduct(String name){
if(name.equals("A"))
return new ProductA();
else return new ProductB();
}
}
- 工厂方法模式
interface SimpleProduct{
void doSomething();
}
class ProductA extends SimpleProduct{
public void doSomething(){
system.out.println("this is Product A");
}
}
class ProductB extends SimpleProduct{
public void doSomething(){
system.out.println("this is Product B");
}
}
class MethodFactory{
public static SimpleProduct getProductA(){
return new ProductA();
}
public static SimpleProduct getProductB(){
return new ProductB();
}
}
- 抽象工厂模式
interface SimpleProduct{
void doSomething();
}
class ProductA extends SimpleProduct{
public void doSomething(){
system.out.println("this is Product A");
}
}
class ProductB extends SimpleProduct{
public void doSomething(){
system.out.println("this is Product B");
}
}
##将工厂抽象成接口
interface AbstractFactory{
SimpleProduct getProduct();
}
class FactoryA implements AbstractFactory{
SimpleProduct getProduct(){
return new ProductA();
}
}
建造者模式
- 建造者模式
class Computer{
private String cpu;
private String disk;
private Computer setCpu(String cpu){
this.cpu = cpu;
return this;
}
}
网友评论