只执行一次某些基类方法调用而不是每个类的实例?

时间:2018-01-05 14:25:56

标签: javascript ecmascript-6

我有一个在实例化时执行登录请求的类,我只想要这个登录请求 由基类和所有其他实例执行以确认登录 已经完成了。任何人都可以推荐如何实现这一目标,这是一个用于制作的用例 登录功能静态?

postsclass PostListAPIView(ListAPIView):
    today = timezone.now()
    def get_queryset(self):
        today = timezone.now()
        articles = Article.objects.all()
        return articles.filter(publish_date__lte=today).order_by('-publish_date')[:30]

    serializer_class = PostSerializer


class PostSerializer(serializers.ModelSerializer):

    publish_date = serializers.DateTimeField(format="%Y-%m-%d %H:%M UTC")

    class Meta:
        model = Article
        fields = "__all__"

1 个答案:

答案 0 :(得分:2)

更好的设计是拥有一个LoginService来管理它。如果已经登录,它将忽略该请求。例如,

class LoginService {
   constructor() {
       this.isLoggedIn = false;
   }
   login() { 
       if (this.isLoggedIn) { return; } 
       // do work
       this.isLoggedIn = true;
   }
}

class Content {
    constructor(loginService) {
        this.loginService = loginService;
        this.performLogin()
    }

    performLogin() { 
        this.loginService.login();
    }

    performLogout() {
        // perform log out once only
    }
}

const loginService = new LoginService();
const contentOne = new ContentOne(loginService);
const contentTwo = new ContentTwo(loginService);

制作函数static不会阻止某些内容被多次调用。