Add factory helper function which returns a singleton

Not that ServiceTypes is super expensive or anything, but it's also
an encapsultation of static data, so there's really no need to construct
more than one of them in a program.

Change-Id: I2515fd9be27421006ed22a3ab01bef8cb48196f8
This commit is contained in:
Monty Taylor 2018-01-12 11:14:03 -06:00
parent b9ce5cf729
commit f9dca6f788
No known key found for this signature in database
GPG Key ID: 7BAE94BC7141A594
3 changed files with 66 additions and 0 deletions

View File

@ -18,3 +18,24 @@ import pbr.version
from os_service_types.service_types import ServiceTypes # flake8: noqa
__version__ = pbr.version.VersionInfo('os-service-types').version_string()
_service_type_manager = None
def get_service_types(*args, **kwargs):
"""Return singleton instance of the ServiceTypes object.
Parameters are all passed through to the
:class:`~os_service_types.service_types.ServiceTypes` constructor.
.. note::
Only one singleton is kept, so if instances with different parameter
values are desired, directly calling the constructor is necessary.
:returns: Singleton instance of
:class:`~os_service_types.service_types.ServiceTypes`
"""
global _service_type_manager
if not _service_type_manager:
_service_type_manager = ServiceTypes(*args, **kwargs)
return _service_type_manager

View File

@ -0,0 +1,38 @@
# -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
test_singleton
------------
Tests for `get_service_types` singleton factory function.
"""
import os_service_types
from os_service_types.tests import base
class TestSingleton(base.TestCase):
def setUp(self):
super(TestSingleton, self).setUp()
# Make an object with no network access
self.service_types = os_service_types.get_service_types()
def test_singleton_same(self):
service_types = os_service_types.get_service_types()
self.assertTrue(service_types is self.service_types)
def test_singleton_different(self):
service_types = os_service_types.ServiceTypes()
self.assertFalse(service_types is self.service_types)

View File

@ -0,0 +1,7 @@
---
features:
- |
Factory function ``os_service_types.get_service_types`` added. Returns
a singleton instance of ServiceTypes. ServiceTypes is a very low cost
object in the first place, but it does read a data file from disk and
then the data is pretty static.