首页 > 解决方案 > 如何在调用同一类的方法时重置初始化

问题描述

下面我有一个工人阶级,有一个 foreach。
在forach里面有服务调用,可以是 GetX()、GetY() ...
作为实现,我必须根据参数重新初始化Api客户端,有没有模式可以避免_aService.SetApiClient(p)行?

public class Worker
    {
        private readonly IAService _aService;

        public Worker(IAService entryPointService)
        {
            _aService = entryPointService;
        }

        protected void ExecuteAsync()
        {
            while (true)
            {
                new List<string>() { "x", "y", "z" }.ForEach(p =>
                {
                    _aService.SetApiClient(p);
                    _aService.GetX();
                    // OR _aService.GetY(),_aService.GetYZ();//
                });

            }
        }
}
        public class AService : IAService
        {
            private GoogleApiClient _googleApiClient;
            public AService(GoogleApiClient apiClient)
            {
                _googleApiClient = apiClient;
            }

            public void SetApiClient(string param)
            {
                _googleApiClient = new GoogleApiClient(new AuthProvider (param));
            }
            public string GetX()
            {
                return _googleApiClient.CallX();
            }
        }

        public interface IAService
        {
            void SetApiClient(string param);
            string GetX();
        }

        public interface IGoogleApiClient
        {
            string CallX();
            string CallY();
            string CallZ();
        }  

public class GoogleApiClient : IGoogleApiClient
    {
        private AuthProvider _param;
        public GoogleApiClient(AuthProvider param)
        {
            _param = param;
        }
        public string CallX()
        {
            return DoSomeCal("X", _param);
        }
        public string CallY()
        {
            return DoSomeCal("Y", _param);
        }
        public string CallZ()
        {
            return DoSomeCal("Z", _param)
        }
    } 

请注意,字符串列表值可以是任何东西

标签: c#design-patterns.net-core

解决方案


您的 api 客户端确实不需要保存状态。(私有字段})它是一个服务/网关类。而是将参数传递给方法 egGetX(string param}。


推荐阅读