Actionscript3 Design Patternsthe Multiton

Title: Actionscript3 Design Patterns:The Multiton Date: 2009-11-10 18:27 Author: eamonnfaherty Category: development Tags: Actionscript, design patterns, multiton Slug: actionscript3-design-patternsthe-multiton

Background Reading
Read about the singleton

The Problem?
You want to have multiple instances of a singleton and want global access to them all. This may be because the objects use groups of resources, such as different groups of sounds, or because the objects need a lot of configuration, such as currency converters, or need global access, an event dispatcher.

Currency converter, sound controller, global event dispatcher

The Multiton:

public class SocketManagerMultiton {
    private static var _instaces : Dictionary;
    public static const CHAT : String = "CHAT";
    public static const WEATHER : String = "WEATHER";

    public static function getInstace(instance:String) : SocketManagerMultiton {
        return _instaces[instance];
private static function ensureInstanceExists(instance:String) : void {
        if (_instaces == null) {
            _instaces = new Dictionary();
        if (_instaces[instance] == null) {
            _instaces[instance] = new SocketManagerMultiton();
    public function send(message : String) : void {

Example Use:

var chatSocket : SocketManagerMultiton = SocketManagerMultiton.getInstace(SocketManagerMultiton.CHAT);
chatSocket.send("hello world");
var weatherSocket : SocketManagerMultiton = SocketManagerMultiton.getInstace(SocketManagerMultiton.WEATHER);

Why is it good?
• It is easy to understand; it is a simple pattern that needs little extra code. It builds on the singleton pattern, which is well known.
• See singleton pattern for other good points.

Why is it bad?
• It tightly couples the classes that use the multiton to the fact that they are using a multiton.
• See singleton pattern for other bad points.

Further Reading
Read about the factory and inversion of control patterns.

Multitons are a way of grouping Singletons. They share the benefits and carry the problems that Singletons have. They are good for classes that use a lot of resources such as socket connections or classes that cache things. They do make code harder to refactor and very difficult to unit test but if follow the suggestions I made in the Singleton post then you can limit your pain, a bit anyway! If you are going to use a multiton make sure you use String constants as I did above. It is easy to make typing mistakes when using String literals. Also the constants can be meaningful, as they are in my example.

Published: November 10 2009

  • category:
  • tags:
blog comments powered by Disqus