好吧,我对编码这种情况的最佳方法有一个疑问: 我有一类需要在所有项目中使用静态变量的类:connection
没有名称空间的单子:
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个唯一变量,它们是整个项目中唯一的静态变量。 我怀疑在这种情况下是否需要单例或者只是静态已经解决了
答案 0 :(得分:1)
我想知道在这种情况下最佳/正确的选择是什么
我绝对会推荐静态类方法。
namespace
是仅TypeScript的功能,许多现成的工具不支持,例如创建React应用。