Proxy Pattern lazy initialize

IHateProxyPattern123 2 года назад обновлен Alexander Shvets 2 года назад 2
I was wondering about the Proxy Pattern description. It suggests to use lazy initialization for the Service Object. How should this work with a database as a service object?? I would have to know what data should be in there to lazy initialize it or am i wrong. The lazy initialization in generel makes no sense to me, would be happy about some clearification.

На рассмотрении


The database connection can be lazy initialized as well. The most common use in regards to databases would probably be a caching proxy. Suppose your server hosts a content management system that loads content from a slow remote database. The server has a fast local memory cache that can store already loaded pieces of content. The proxy could implement this behavior, fetching content from the fast memory cache if it's there and defaulting to the slow database if not.

In this scenario, when do you establish the database connection?

— You can do it right in the Proxy constructor. This will slow down the initialization phase, but the database connection will be ready by the time the proxy has to call the database.

— Or you can go with the lazy loading approach, establishing the database connection only if the proxy needs to call the database (this may never happen if the cache is full). The initialization of the proxy will be much faster as you don't wait for the database, but the first request to the database will be slower, as you'll need to establish the connection first. However, if all the required content is already in the memory cache, the proxy might never need to call the database, and thus that slow down on the first request is not critical.

Сервис поддержки клиентов работает на платформе UserEcho