Singleton object:
只能生成一个instance, 就叫singleton object
public class CSingleton
{
private static CSingleton instance;
private CSingleton(){}
public static CSingleton getInstance(){
if(instance== null){
instance= new CSingleton();
}
return instance;
}
};
调用时:
public class SingletonPatternDemo {
public static void main(String[] args) {
//Get the only object available
CSingleton object = CSingleton.getInstance();
}
}
下面是Singleton与static class的区别。
Singleton object stores in Heap but, static object stores in Stack
We can clone the object of Singleton but, we can not clone the static class object
Singleton class follow the OOP(object oriented principles) but not static class
we can implement interface with Singleton class but not with Static class.
JAVA static变量:
记:static method 和 static variable 都不用创建 instance,可以类名直接引用。
http://crunchify.com/java-static-methods-variables-static-block-and-class-with-example/
http://blog.csdn.net/zhandoushi1982/article/details/8453522
static的好处是:全局唯一,一改都改。同时引用方便。
static final:全局固定常量
工厂模式:
http://blog.csdn.net/jason0539/article/details/23020989
使用不同factory to create 不同的class,product。Client just need to create the instance to factory. 不用考虑具体product是如何create,生产的。
产品:
abstract class BMW {
public BMW(){
}
}
public class BMW320 extends BMW {
public BMW320() {
System.out.println("制造-->BMW320");
}
}
public class BMW523 extends BMW{
public BMW523(){
System.out.println("制造-->BMW523");
}
}
工厂:
interface FactoryBMW {
BMW createBMW();
}
public class FactoryBMW320 implements FactoryBMW{
@Override
public BMW320 createBMW() {
return new BMW320();
}
}
public class FactoryBMW523 implements FactoryBMW {
@Override
public BMW523 createBMW() {
return new BMW523();
}
}
Client:
public class Customer {
public static void main(String[] args) {
FactoryBMW320 factoryBMW320 = new FactoryBMW320();
BMW320 bmw320 = factoryBMW320.createBMW();
FactoryBMW523 factoryBMW523 = new FactoryBMW523();
BMW523 bmw523 = factoryBMW523.createBMW();
}
}
State Machine Design Pattern
Similar to the State design pattern, a class behavior changes based on its state. And State Machine is the same as an intent of State: to make it possible for an object to alter its behavior when its internal state changes. It contains three main classes: State class, Event class, and Context class.
Context classes implements transition logic, and the next state is done by notifying the Context class with an event. State class transits to other state by passing Event to Context.
SNAKE原则
Scenario: case/interface
Necessary: constrain/hypothesis
Application: service/algorithm
Kilobit: Data
Evolve:
比如,design a FM Radio
Steps 1: Enumerate use cases,
Register/Login, Play Music, Music recommendation. 并说明,最重要的feature是什么。
Steps 2: Sort
Priority 1. Play Music
get channels, select channel, play music in this channel