好吧,我有一个关于编码这种情况的最佳方法的问题:我有一个需要在所有项目中使用静态变量的类:连接
没有名称空间的单例:
class Broker {
static connection: Connection = undefined;
static channel: Channel = undefined;
static urli: string = process.env.RABBIT_URL || 'url';
static start() {
return new Promise<Connection>((resolve, reject) => {
if (Broker.connection || !Broker.urli) {
const message = !Broker.urli
? 'The host of rabbitmq was not found in the environment variables'
: 'Connection has already been established';
logger.info(message);
reject(new Error(message));
}
retry<Connection>(() => connect(Broker.urli), 10, 1000)
.then((conn) => {
Broker.connection = conn;
resolve(conn);
})
.catch((err) => reject(new Error(err)));
});
}
}
export const ConnectionMQ: Connection = Broker.connection;
export const ChannelMQ: Channel = Broker.channel;
export const start = () => {
return Broker.start();
};
与名称空间
//namespace
namespace Broker {
export type QueuesToAssert = { queue: string; options?: Options.AssertQueue };
export type ExchangesToAssert = {
exchange: string;
type: string;
options?: Options.AssertExchange;
};
export type QueuesToBind = {
queue: string;
source: string;
pattern: string;
args?: any;
};
//static
class BrokerMain {
static connection: Connection = undefined;
static channel: Channel = undefined;
static urli: string = process.env.RABBIT_URL || 'url';
static start() {
return new Promise<Connection>((resolve, reject) => {
if (BrokerMain.connection || !BrokerMain.urli) {
const message = !BrokerMain.urli
? 'The host of rabbitmq was not found in the environment variables'
: 'Connection has already been established';
logger.info(message);
reject(new Error(message));
}
retry<Connection>(() => connect(BrokerMain.urli), 10, 1000)
.then((conn) => {
this.connection = conn;
resolve(conn);
})
.catch((err) => reject(new Error(err)));
});
}
}
export const Connection = BrokerMain.connection;
export const Channel = BrokerMain.channel;
export const start = () => {
return BrokerMain.start();
};
export const close = () => {};
}
//usage
const connection = Broker.Connection ? Broker.start() : undefined;
我想知道在这种情况下最好/正确的选择是什么,或者我是否可以对这种情况应用另一种方法。记住我只需要类的2个唯一变量,它们是整个项目中唯一的静态变量。我怀疑在这种情况下是否需要单例或只是静态已经解决了
我想知道在这种情况下最佳/正确的选择是什么,
我绝对会推荐静态类方法。
namespace
是仅TypeScript功能,许多开箱即用的工具(例如Create React App)不支持。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句