[Add] MessageSenderBuilder, MessageSenderFactory 增加用于创建MessageSender而又与平台无关的Builder, 初步增加对应Factory;

This commit is contained in:
2020-04-21 22:43:24 +08:00
parent 620c3785ad
commit 73ae9a268b
6 changed files with 104 additions and 0 deletions

View File

@ -0,0 +1,43 @@
package net.lamgc.cgj.bot.message;
import java.util.concurrent.atomic.AtomicReference;
/**
* 消息发送器构造
*/
public final class MessageSenderBuilder {
private final static AtomicReference<MessageSenderFactory> currentFactory = new AtomicReference<>();
private MessageSenderBuilder() {}
/**
* 获取消息发送器
* @param source 消息源类型
* @param id 消息源Id
* @return 返回新建的发送器
*/
public static MessageSender getMessageSender(MessageSource source, long id) {
MessageSenderFactory messageSenderFactory = currentFactory.get();
if(messageSenderFactory == null) {
throw new IllegalStateException("The factory is not ready");
}
try {
return messageSenderFactory.createMessageSender(source, id);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
/**
* 设置消息发送器工厂
* @param factory 工厂对象
*/
public static void setCurrentMessageSenderFactory(MessageSenderFactory factory) {
if(currentFactory.get() != null) {
throw new IllegalStateException("Factory already exists");
}
currentFactory.set(factory);
}
}

View File

@ -0,0 +1,13 @@
package net.lamgc.cgj.bot.message;
public interface MessageSenderFactory {
/**
* 通过Id创建发送器
* @param source 消息源
* @param id 消息源id
* @return 如果成功返回MessageSender
*/
MessageSender createMessageSender(MessageSource source, long id) throws Exception;
}

View File

@ -0,0 +1,25 @@
package net.lamgc.cgj.bot.message;
import net.mamoe.mirai.Bot;
public class MiraiMessageSenderFactory implements MessageSenderFactory {
private final Bot bot;
public MiraiMessageSenderFactory(Bot bot) {
this.bot = bot;
}
@Override
public MessageSender createMessageSender(MessageSource source, long id) throws Exception {
switch(source) {
case Group:
case Discuss:
return new MiraiMessageSender(bot.getGroup(id), source);
case Private:
return new MiraiMessageSender(bot.getFriend(id), source);
default:
throw new NoSuchFieldException(source.toString());
}
}
}

View File

@ -0,0 +1,17 @@
package net.lamgc.cgj.bot.message;
import net.lz1998.cq.robot.CoolQ;
public class SpringCQMessageSenderFactory implements MessageSenderFactory {
private final CoolQ coolQ;
public SpringCQMessageSenderFactory(CoolQ coolQ) {
this.coolQ = coolQ;
}
@Override
public MessageSender createMessageSender(MessageSource source, long id) {
return new SpringCQMessageSender(coolQ, source, id);
}
}