Home > Software design >  Instantiate with different classes?
Instantiate with different classes?

Time:02-04

This might sound dump, but can I do such thing:

public class CameraConnection
{
    Object camera;
    public CameraConnection(bool isNewCamera)
    {
        if(isNewCamera)
        {
            camera = new Camera1();
            
        }
        else
        {
            camera = new Camera2();
        }
    }
    public void TakeImage()
    {
        camera.TakeImage();
    }
}

So here I can call camera.TakeImage() for taking an image, but base on which class the variable camera is instantiated (Camera1 or Camera2) it actually uses differrent camera APIs..

I feel like this is somewhat related to class abstraction or interface but not really sure...

Thanks a lot!

CodePudding user response:

define an interface the defines the behavior of a camera.

public interface ICamera{
  void TakePhoto();
  int HowManyPicsInCamera();
  .....
  // all the things a camera object needs to do
}

now have some classses that implement it

public class Camera1:ICamera{
    void TakeShot(){
    }
     int HowManyPicsInCamera(){
    }
}


public class Camera2:ICamera{
    void TakeShot(){
    }
     int HowManyPicsInCamera(){
    }
}

now use that

public class CameraConnection
{
    ICamera camera;
    public CameraConnection(bool isNewCamera)
    {
        if(isNewCamera)
        {
            camera = new Camera1();
            
        }
        else
        {
            camera = new Camera2();
        }
    }
    public void TakeImage()
    {
        camera.TakeImage();
    }
}

alternatively you can use a base class, you do that if there is common implementation details. Like common data or code.

CodePudding user response:

It is related to class abstraction, inheritance to be exact.

For example:

public class BaseCamera {}

public class Camera1 : BaseCamera {}

public class Camera2 : BaseCamera {}

This will then allow you to instantiate multiple camera types based on the parent class. I recommend nuking object as the type because the compiler won't be able to resolve camera.TakeImage() for example.

  •  Tags:  
  • Related