java链式编程设计

时间:2023-03-09 19:14:12
java链式编程设计

一般情况下,对一个类的实例和操作,是采用这种方法进行的:

Channel channel = new Channel();
channel.queueDeclare(QUEUE_NAME, true, false, false, null);
int prefetchCount = 1;
channel.basicQos(prefetchCount);
byte[] bytes = message.getBytes("UTF-8");
channel.basicPublish("",bytes);

上面是一个Channel类,对它的创建和操作我们一般会采用这种方法进行。但有些情况下,这很烦琐。

因此,可考虑以另一种形式设计类:如

public class Channel {

    private int basicQos=0;
private AMQP.Queue queue;
public Channel()
{} public Channel basicQos(int preCnt)
{
this.basicQos=preCnt;
return this;
}
public Channel queueDeclare(String queue, boolean durable, boolean exclusive, boolean autoDelete,
Map<String, Object> arguments)
{
this.queue=createQueue();
return this;
} private AMQP.Queue createQueue()
{
return new AMQP.Queue();
} public void basicPublish(String exchange,byte[] bytes)
{
//doSomething
}
}

所以就可以这样构造,以链的形式,如:

 @Test
public void testChannel()
{
new Channel().basicQos(1).queueDeclare("",true,false,false,null).basicPublish("",new byte[]{1,3,4}); }