单一职责原则(Single Responsibility Principle) - 这里的设计模式原则,主要讨论的是Java面向对象编程设计中设计原则,单一职责原则由于其适用的普遍性,个人认为不放在六大原则之中
- 单一职责原则 :一个类只负责一项职责
- 不能存在多于一个导致类变更的原因
- 单一职责原则符合"高内聚,低耦合"的思想
- 单一职责原则不只是面向对象编程思想所特有的,只要是模块化的程序设计,都适用单一职责原则
工厂方法模式分为三种 :普通工厂模式,多个工厂方法模式,静态工厂方法模式
--- 发送邮件和短信
- 接口
public interface Sender{
public void Send();
}
- 实现类
public class MailSender implements Sender{
@Override
public void Send(){
System.out.println("MailSender Method");
}
}
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
public class SmsSender implements Sender{
@Override
public void Send(){
System.out.println("SmsSender Method");
}
}
- 工厂类
public class SendFactory{
public Sender produce(String type){
if("mail".equals(type)){
return new MailSender();
}else if("sms".equals(type)){
return new SmsSender();
}else{
System.out.println("Please input right type!");
}
}
}
- 测试类
public class FactoryTest{
public static void main(String[] args){
SendFactory factory=new SendFactory();
Sender sender=factory.produce("sms");
sender.Send();
}
}
- SendFactory类
public class SendFactory{
public Sender produceMail(){
return new MailSender();
}
public Sender produceSms(){
return new SmsSender();
}
}
- 测试类
public class FactoryTest{
public static void main(String[] args){
SendFactory factory=new SendFactory();
Sender sender=factory.produceMail();
sender.Send();
}
}
- SendFactory
public class SendFactory{
public static Sender produceMail(){
return new MailSender();
}
public static Sender produceSms(){
return new SmsSender();
}
}
- FactoryTest
public class FActoryTest{
public static void main(String[] args){
Sender sender=SenderFactory.produceMail();
sender.Send();
}
}
- Sender
public interface Sender{
public void Sender();
}
- 两个实现类
- MailSender
public class MailSender implements Sender {
@Override
public void Send(){
System.out.println("This is MailSender!");
}
}
- SmsSender
public class SmsSender implements Sender{
@Override
public void Send(){
System.out.println("This is SmsSender!");
}
}
- 两个工厂类
- 工厂类接口:
public interface Provider{
public Sender produce();
}
- SendMailFactory
public class SendMailFactory implements Provider{
@Override
public Sender produce(){
return new MailSender();
}
}
- SendSmsFactory
public class SendSmsFactory implements Provider{
@Override
public Sender produce(){
return new SmsSender();
}
}
- Test
public class Test{
public static void main(String[] args){
Provider provider=new SendMailFactory();
Sender sender=provider.produce();
sender.Send();
}
}
- 单例类
public class Singleton{
/* 私有静态实例,防止被引用,赋值为null,目的是实现延迟加载 */
private static Singleton instance=null;
/* 私有构造方法,防止被实例化 */
private Singleton(){
}
/* 静态工厂方法,创建实例 */
public static Singleton getInstance(){
if(instance==null){
instance=new Singleton();
}
return instance;
}
/* 如果该对象被用于序列化,可以保证对象在序列化前后保持一致 */
public Object ReadResolve(){
return instance;
}
}
public static synchronized Singleton getInstance(){
if(instance==null){
instance=new Singleton();
}
return instance;
}
由于synchronized锁住的是这个对象,这样的用法,每次调用getInstance(),都要对对象上锁,在性能上会有所下降.
public static Singleton getInstance(){
if(instance==null){
synchronized(instance){
if(instance==null){
instance=new Singleton();
}
}
}
return instance;
}
这样似乎解决了问题,将synchronized关键字加入内部,这样在调用的时候是不需要加锁的,只有在instance为null,并创建对象的时候才需要的加锁,性能得到了提升,但是这样的情况还是有问题的
private static class SingletonFactory{
private static Singleton instance=new Singleton();
}
public static Singleton getInstance(){
return SingletonFactory.instance;
}
public class Singleton{
/* 私有构造方法,防止被实例化 */
private Singleton(){
}
/* 使用内部类维护单例 */
private static class SingletonFactory{
private static Singleton instance=new Singleton();
}
/* 获取实例 */
public static Singleton getInstance(){
return SingletonFactory.instance;
}
/* 如果该对象被序列化,可以保证对象在序列化前后保持一致 */
public Object readResolve(){
return getInstance();
}
}
这种方法,如果在构造函数中抛出异常,实例将永远不会创建,也会出错.
只能根据实际场景,选择最适合应用场景的实现方法
public class SingletonTest{
private static SingletonTest instance=null;
private SingletonTest(){
}
private static synchronized void syncInit(){
if(instance==null){
instance=new SingletonTest();
}
}
public static SingletonTest getInstance(){
if(instance==null){
syncInit();
}
return instance;
}
}
public class SingletonTest{
private static SingletonTest instance=null;
private Vector properties=null;
public Vector getProperties(){
return properties;
}
private SingletonTest(){
}
private static synchronized void syncInit(){
if(instance==null){
instance=new SingletonTest();
}
}
public static SingletonTest getInstance(){
if(intance==null){
syncInit();
}
return instance;
}
public void updateProperties(){
SingletonTest shadow=new SingletonTest();
properties=shadow.getProperties();
}
}
- Builder
public class Builder{
private List<Sender> list=new ArrayList<Sender>();
public void produceMailSender(int count){
for(int i=0;i<count;i++){
list.add(new MailSender());
}
}
public void produceSmsSender(int count){
for(int i=0;i<count;i++){
list.add(new SmsSender());
}
}
}
- 测试类
public class Test{
public static void main(String[] args){
Builder builder=new Builder();
builder.produceMailSender(10);
}
}
- 原型类
public class Prototype implements Cloneable{
public Object clone() throws CloneNotSupportedException{
Prototype proto=(Prototype)super.clone();
return proto;
}
}
public class Prototype implements Cloneable,Serializable{
private static final long serialVersionUID=1L;
private String string;
private SerializableObject obj;
/* 浅复制 */
public Object clone() throws CloneNotSupportedException{
Prototype proto=(Prototype)super.clone();
return proto;
}
/* 深复制 */
public Object clone() throws IOException,ClassNotFoundException{
/* 写出当前对象的二进制流 */
ByteArrayOutputStream bos=new ByteArrayOutputStream();
ObjectOutputStream oos=new ObjectOutputStream(bos);
oos.writeObject(this);
/* 读入二进制流产生的新对象 */
ByteArrayInputStream bis=new ByteArrayInputStream(bos.toByteArray());
OnjectInputStream ois=new ObjectInputStream(bis);
return ois.readObject();
}
public String getString(){
return string;
}
public void setString(String string){
this.string=string;
}
public SerializableObject getObj(){
return obj;
}
public void setObj(SerializableObject obj){
this.obj=obj;
}
}
class SerializableObject implements Serializable{
private static final long serialVersionUID=1L;
}
- Source
public class Source{
public void method1(){
System.out.println("This is original method!");
}
}
- Targetable
public interface Targetable{
/* 与原类中的方法相同 */
public void method1();
/* 新类方法 */
public void method2();
}
- Adapter
public class Adapter extends Source implemments Targetable{
@Override
public void method2(){
System.out.println("This is the targetable method!");
}
}
- AdapterTest
public class AdapterTest{
public static void main(String[] args){
Targetable target=new Adapter();
target.method1();
target.method2();
}
}
- Wrapper
public class Wrapper implements Targetable{
private Source source;
public Wrapper(Source source){
super();
this.source=source;
}
@Override
public void method1(){
source.method1();
}
@override
public void method2(){
System.out.println("This is the targetable method!");
}
}
- Test
public class AdapterTest{
public static void main(String[] args){
Source source=new Source();
Targetable target=new Wrapper(source);
target.method1();
target.nethod2();
}
}
- Sourceable
public interface Sourceable{
public void method1();
public void method2();
}
- Wrapper-抽象类
public abstract class Wrapper implements Sourceable{
public void method1(){
}
public void method2(){
}
}
- SourceSub1
public class SourceSub1 extends Wrapper{
public void method1(){
System.out.println("The sourceable interface's first Sub");
}
}
- SourceSub2
public class SourceSub2 extends Wrapper(){
public void method2(){
System.out.println("The Sourceable interface's second Sub");
}
}
- WrapperTest
public class WrapperTest{
public static void main(String[] args){
Sourceable source1=new SourceSub1();
Sourceable source2=new SourceSub2();
source1.method1();
source1.method2();
source2.method1();
source2.method2();
}
}
- Sourceable
public interface Sourceable{
public void method();
}
- Source
public class Source implements Sourceable{
@Override
public void method(){
System.out.println("The original method!");
}
}
- Decorator
public class Decorator implements Sourceable{
private Sourceable source;
public Decorator(Sourceable source){
super();
this.source=source;
}
@Override
public void method(){
System.out.println("Before decorator!");
source.method();
System.out.println("After decorator!");
}
}
-Test
public class DecoratorTest{
public static void main(String[] args){
Sourceable source=new Source();
Sourceable obj=new Decorator(source);
obj.method();
}
}
- Sourceable
public interface Sourceable{
public void method();
}
- Source
public class Source implements Sourceable{
@Override
public void method(){
System.out.println("The original method!");
}
}
- Proxy
public class Proxy implements Sourceable{
private Source source;
public Proxy(){
super();
this.source=new Source;
}
@Override
public void method(){
before();
source.method();
after();
}
public void before(){
System.out.println("Before Proxy!");
}
public void after(){
System.out.println("After Proxy!");
}
}
- ProxyTest
public class ProxyTest{
public static void main(String[] args){
Sourceable source=new Proxy();
source.method();
}
}
- CPU
public class CPU{
public void startup(){
System.out.println("CPU startup!");
}
public void shutdown(){
System.out.println("CPU shutdown!");
}
}
- Memory
public class Memory{
public void startup(){
System.out.println("Memory startup!");
}
public void shutdown(){
System.out.println("Memory shutdown!");
}
}
- Disk
public class Disk{
public void startup(){
System.out.println("Disk startup!");
}
public void shutdown(){
System.out.println("Disk shutdown!");
}
}
- Computer
public class Computer{
private CPU cpu;
private Memory memory;
private Disk disk;
public Computer(){
cpu=new CPU();
memory=new Memory();
disk=new Disk();
}
public void startup(){
System.out.println("Start the computer!");
cpu.startup();
memory.startup();
disk.startup();
System.out.println("Start the computer finished!");
}
public void shutdown(){
System.out.println("Begin to close the computer!");
cpu.shutdown();
memory.shutdown();
disk.shutdown();
System.out.println("Computer closed!");
}
}
-User
public class User{
public static void main(String[] args){
Computer computer=new Computer();
computer.startup();
computer.shutdown();
}
}
- Sourceable
public interface Sourceable{
public void method();
}
- SourceSub1
public class SourceSub1 implements Sourceable{
@Override
public void method(){
System.out.println("This is the first sub!");
}
}
- SourceSub2
public class SourceSub2 implements Sourceable{
@Override
public void method(){
System.out.println("This is the second sub!");
}
}
- 定义一个桥,持有Sourceable的一个实例
public abstract class Bridge{
private Sourceable source;
public void method(){
source.method();
}
public Sourceable getSource(){
return source;
}
public void getSource(Sourceable source){
this.source=source;
}
}
- MyBridge
public class MyBridge extends Bridge{
public void method(){
getSource().method();
}
}
- BridgeTest
public class BridgeTest{
public static void main(String[] args){
Bridge bridge=new MyBridge();
/* 调用第一个对象 */
Sourceable source1=new SourceSub1();
bridge.setSource(source1);
bridge.method();
/* 调用第二个对象 */
Sourceable source2=new SourceSub2();
bridge.setSource(source2);
bridge.method();
}
}
- TreeNode
public class TreeNode{
private String name;
private TreeNode parent;
private Vector<TreeNode> children=new Vector<TreeNode>();
public TreeNode(String name){
this.name=name;
}
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
public TreeNode getParent(){
return parent;
}
public void setParent(TreeNode parent){
this.parent=parent;
}
/* 添加孩子节点 */
public void add(TreeNode node){
children.add(node);
}
/* 删除孩子节点 */
public void remove(TreeNode node){
children.remove(node);
}
/* 获得孩子节点 */
public Enumeration<TreeNode> getChildren(){
return children.elements();
}
}
- Tree
public class Tree{
TreeNode root=null;
public Tree(String name){
root=new TreeNode(name);
}
public void main(String[] args){
Tree tree=new Tree("A");
TreeNode nodeB=new TreeNode("B");
TreeNode nodeC=new TreeNode("C");
nodeB.add(nodeC);
tree.root.add(nodeB);
System.out.println("Build the tree finished!");
}
}
public class ConnectionPool{
private Vector<Connection> pool;
/* 公有属性 */
private String url="jdbc:mysql://localhost:3306/test";
private String username="root";
private String password="root";
private String driverClassName="com.mysql.jdbc.Driver";
private int poolSize=100;
private static ConnectionPool instance=null;
Connection conn=null;
/* 构造方法,负责初始化 */
private ConnectionPool(){
pool = new Vector<Connection>(poolSize);
for(int i=0;i<poolSize;i++){
try{
Class.forName(driverClassName);
conn=DriverManager.getConnection(url,user,password);
pool.add(conn);
}catch(ClassNotFoundException e){
e.printStackTrace();
}catch(SQLEXception e){
e.printStackTrace();
}
}
}
/* 返回连接到连接池 */
public sysnchronized void release(){
pool.add(conn);
}
/* 返回连接池中的一个数据库 */
public syschronized Connection getConnection(){
if(pool.size()>0){
Connection conn=pool.get(0);
pool.remove(conn);
return conn;
}else{
return null;
}
}
}
- ICalculator
public interface ICalculator{
public int calculate(String exp);
}
- AbstractCalculator
public abstract class AbstractCalcuator{
public int[] split(String exp,String opt){
String array[]=exp.split(opt);
int arrayInt[]=new int[2];
arrayInt[0]=Integer.parseInt(array[0]);
arrayInt[1]=Integer.parseInt(array[1]);
return arrayInt;
}
}
- Plus
public class Plus extends AbstractCalculator implements ICalculator{
@Override
public int calculate(String exp){
int arrayInt[]=split(exp,"\\+");
return arrayInt[0]+arrayInt[1];
}
}
- Minus
public class Minus extends AbstractCalculator implements ICalculator{
@Override
public int calculate(String exp){
int arrayInt[]=split(exp,"-");
return arrayInt[0]-arrayInt[1];
}
}
- Multiply
public class Multiply extends AbstractCalculator implements ICalculator{
@Override
public int calculate(String exp){
int arrayInt[]=split(exp,"\\*");
return arrayInt[0]*arrayInt[1];
}
}
- StrategyTest
public class StrategyTest{
public static void mian(String[] args){
String exp="2+8";
ICalculator cal=new Plus();
int result=cal.calculate(exp);
System.out.println(result);
}
}
public abstract class AbstractCalculator{
/* 主方法,实现对本类的其它方法的调用 */
public final int calculate(String exp,String opt){
int array[]=split(exp,opt)
return calculate(array[0],array[1]);
}
/* 抽象方法,需要子类进行重写 */
abstract public int calculate(int num1,int num2);
public int[] split(String exp,String opt){
String array[]=exp.split(opt);
int arrayInt[]=new int[2];
arrayInt[0]=Integer.parseInt(array[0]);
arrayInt[1]=Integer.parseInt(array[1]);
return arrayInt;
}
}
- Plus
public class Plus extends AbstractCalculator{
@Override
public int calculate(int num1,int num2){
return num1+num2;
}
}
- StrategyTest
public class StrategyTest{
public static void main(String[] args){
String exp="8+8";
AbstractCalculator cal=new Plus();
int result=cal.calculate(exp,"\\+");
System.out.println(result);
}
}
Test的执行过程:
- Observer
public interface Observer{
public void update();
}
- Observer1
public class Observer1 implements Observer{
@Override
public void update(){
System.out.println("Observer1 has received!");
}
}
- Observer2
public class Observer2 implements Observer{
@Override
public void update(){
System.out.println("Observer2 has received!");
}
}
- Subject
public interface Subject{
/* 增加观察者 */
public void add(Observer observer);
/* 删除观察者 */
public void del(Observer observer);
/* 通知所有观察者 */
public void notifyObservers();
/* 自身的操作 */
public void operation();
}
- AbstractSubject
public abstract class AbstractSubject implements Subject{
private Vector<Observer> vector=new Vector<Observer>();
@Override
public void add(Observer observer){
vector.add(observer);
}
@Override
public void del(Observer observer){
vector.remove(observer);
}
@Override
public void notifyObservers(){
Enumeration<Observer> enumo=vector.elements();
while(enumo.hasMoreElements()){
enumo.nextElement().update();
}
}
}
- MySubject
public class MySubject extends AbstractSubject{
@Override
public void operation(){
System.out.println("update self!");
notifyObservers();
}
}
- ObserverTest
public class ObserverTest{
public static void main(String[] args){
Subject sub=new MySubject();
sub.add(new Observer1());
sub.add(new Observer2());
sub.operation();
}
}
- Collection
public interface Collection{
public Iterator iterator();
/* 取得集合元素 */
public Object get(int i);
/* 取得集合大小 */
public int size();
}
- Iterator
public interface Iterator{
// 前移
puublic Object previous();
// 后移
public Object next();
public boolean hasNext();
// 取得第一个元素
public Object first();
}
- MyCollection
public class MyCollection implements Collection{
public String string[]={
"A","B","C","D","E"};
@Override
public Iterator iterator(){
return new MyIterator(this);
}
@Override
public Object get(int i){
return string[i];
}
@Override
public int size(){
return string.length;
}
}
- MyIterator
public class MyIterator implements Iterator{
private Collection collection;
private int pos=-1;
public MyIterator(Collection collection){
this.collection=collection;
}
@Override
pbulic Object previous(){
if(pos>0){
pos--;
}
return collection.get(pos);
}
@Override
public Object next(){
if(pos<collection.size()-1){
pos++;
}
return collection.get(pos);
}
@Override
public Object hasNext(){
if(pos<collection.size()-1){
return true;
}else{
return false;
}
}
@Override
public Object first(){
pos=0;
return collection.get(pos);
}
}
- Test
public class Test{
Collection collection=new MyCollection();
Iterator it=collection.iterator();
whhile(it.hasNext()){
System.out.println(it.next());
}
}
- Handler
public interface Handler{
public void operator();
}
- AbstractHandler
public abstract class AbstractHandler{
private Handler handler;
private Handler getHandler(){
return handler;
}
private void setHandler(Handler handler){
this.handler=handler;
}
}
- MyHandler
public class MyHandler extends AbstractHandler implements Handler{
private String name;
public MyHandler(String name){
this.name=name;
}
@Override
public void operator(){
System.out.println(name+"deal!");
if(getHandler()!=null){
getHandler().operator();
}
}
}
- Test
public class Test{
public static void main(String[] args){
MyHandler h1=new MyHandler("h1");
MyHanlder h2=new MyHandler("h2");
MyHandler h3=new MyHandler("h3");
h1.setHandler(h2);
h2.setHandler(h3);
h1.operator();
}
}
- Command
public interface Command{
public void exe();
}
- MyCommand
public class MyCommand implements Command{
private Receiver receiver;
public MyCommand(Receiver receiver){
this.receiver=receiver;
}
@Override
public void exe(){
receiver.action();
}
}
- Receiver
public class Receiver{
public void action(){
System.out.println("Command Received!");
}
}
- Invoker
public class Invoker{
private Command command;
public Invoker(Command command){
this.command=command;
}
public void action(){
command.exe();
}
}
- Test
public class Test{
public static void main(String[] args){
Receiver receiver=new Receiver();
Command cmd=new MyCommand(receiver);
Invoker Invoker=new Invoker(cmd);
invoker.action();
}
}
- Original
public class Original{
private String value;
private String getValue(){
return value;
}
private void setValue(String value){
this.value=value;
}
public Original(String value){
this.value=value;
}
public Memento createMemento(){
return new Memento(value);
}
public void restoreMemento(Memento memento){
this.value=memento.getValue();
}
}
- Memento
public class Memento{
private String value;
public Memento(String value){
this.value=value;
}
public String getValue(){
return value;
}
public void setValue(String value){
this.value=value;
}
}
- Storage
public class Storage{
private Memento memento;
public Storage(Memento memento){
this.memento=memento;
}
public Memento getMemento(){
return memento;
}
public void setMemento(Memento memento){
this.memento=memento;
}
}
- Test
public class Test{
public static void main(String[] args){
// 创建原始类
Original original=new Original("egg");
// 创建备忘录
Storage storage=new Storage(original.createMemento());
// 修改原始类的状态
System.out.println("初始状态为:"+original.getValue());
original.setValue("bulk");
System.out.println("修改后的状态:"+original.getValue());
// 恢复原始类的状态
original.restoreMemento(storage.getMemento());
System.out.println("恢复后的状态为:"+original.getValue());
}
}
- State
public class State{
private String value;
private String getValue(){
return value;
}
private void setValue(String value){
this.value=value;
}
public void method1(){
System.out.println("Execute the first opt!");
}
public void method2(){
System.out.println("Execute the second opt!");
}
}
- Context
public class Context{
private State state;
private Context(State state){
this.state=state;
}
public State getState(){
return state;
}
public void setState(){
this.state=state;
}
public void method(){
if(state.getValue().equals("state1")){
state.method1();
}else if(state.getValue().equals("state2")){
state.method2();
}
}
}
- Test
public class Test{
public static void main(String[] args){
State state=new State();
Context context=new Context(state);
// 设置第一种状态
state.setValue("state1");
context.method();
// 设置第二种状态
state.setValue("state2");
context.method();
}
}
- Visitor
public interface Visitor{
public void visit(Subject sub);
}
- MyVisitor
public class MyVisitor implements Visitor{
@Override
public void visit(Subject sub){
System.out.println("visit the subject:"+sub.getSubject());
}
}
- Subject
public interface Subject{
public void accept(Visitor visitor);
public String getSubject();
}
- MySubject
public class MySubject implements Subject{
@Override
public void accept(Visitor visitor){
visitor.visit(this);
}
@Override
public String getSubject(){
return "love";
}
}
- Test
public class Test{
public static void main(String[] args){
Visitor visitor=new MyVisitor();
Subject sub=new MySubject();
sub.accept(visitor);
}
}
- Mediator
public interface Mediator{
public void createMediator();
public void workAll();
}
- MyMediator
public class MyMediator implements Mediator{
private User user1;
private User user2;
public User getUser1(){
return user1;
}
public User getUser2(){
return user2;
}
@Override
public void createMediator(){
user1=new User1(this);
user2=new User2(this);
}
@Override
public void workAll(){
user1.work();
user2.work();
}
}
- User
public abstract class User{
private Mediator mediator;
public Mediator getMediator(){
return mediator;
}
public User(Mediator mediator){
this.mediator=mediator;
}
public abstract void work();
}
- User1
public class User1 extends User{
public User1(Mediator mediator){
super(mediator);
}
@Override
public void work(){
System.out.println("user1 exe!");
}
}
- User2
public User2 extends User{
public User2(Mediator mediator){
super(mediator);
}
@Override
public void work(){
System.out.println("user2 exe!");
}
}
- Test
public class Test{
public static void main(String[] args){
Mediator mediator=new MyMediator();
mediator.createMediator();
mediator.workAll();
}
}
- Expression
public interface Expression{
public int interpret(Context context);
}
- Plus
public class Plus implements Expression{
@Override
public int interpret(Context context){
return context.getNum1()+context.getNum2();
}
}
- Minus
public class Minus implements Expression{
@Override
public void interpret(Context context){
return context.getNum1()-context.getNum2();
}
}
- Context
public class Context{
private int num1;
private int num2;
public Context(int num1,int num2){
this.num1=num1;
this.num2=num2;
}
public int getNum1(){
return num1;
}
public void setNum1(int num1){
this.num1=num1;
}
public int getNum2(){
return num2;
}
public void setNum2(int num2){
this.num2=num2;
}
}
- Test
public class Test{
public static void main(String[] args){
// 计算 9+2-8
int result=new Minus().interpret((new Context(new Plus().interpret(new Context(9,2)),8)));
System.out.println(result);
}
}