Different classes implementing same interface goes into constructor - oop

This is a question about abstraction.
I want to be able to use two completely different GUIs for my application. They are completely different but implements the same interface.
My question is, what will the constructor look like? What type of object goes in the signature?
They do not extend a common parent, so I can't use polymorphism.
controller object wants to be injected with an object which implements Displayable interface.
interface Displayable {
void display();
}
class Display1 implements Displayable {
public void display() {
//Shows something Fancy on the screen
}
}
class Display2 implements Displayable {
public void display() {
//write something to console
}
}
class Main {
public static void main(String[] args) {
// Controller controller = new Controller(new Display1());
Controller controller = new Controller(new Display2());
controller.display();
}
}
class Controller {
????? display;
public Controller(?????? display) {
this.display = display;
}
public void display() {
display.display();
}
}

Related

Is this considered as good approach of using interface type in class

Say i have a code as follows
interface Interface1
{
void method1();
}
interface Interface2
{
void method2();
}
class ClassWithInterfaces : Interface1,Interface2
{
void method1(){}
void method2(){}
}
Now in my "manager" class i implement this as follows :
public OtherClass
{
Interface1 interface1;
Interface2 interface2;
public void someMethod()
{
ClassWithInterfaces classWithInterfaces = new ClassWithInterfaces();
interface1 = classWithInterfaces;
interface2 = classWithInterfaces
}
}
I don't feel that this is the right way to do it hovewer i can't come up with other solutions i can't use Dependency Injection Frameworks in my project if you ask about that. Can you tell me wheter apart from DI there is a better way of doing that?
Hello and welcome to Stack Overflow :-)
You don't have to use a framework in order to do DI. In fact, there are some languages that make it impossible to use a framework for DI - e.g., C++.
Any way, in your case, the proper way to do DI is like this:
interface Interface1
{
void method1();
}
interface Interface2
{
void method2();
}
interface Interface3 : Interface1, Interface2
{
void method1();
void method2();
}
class ClassWithInterfaces : Interface3
{
void method1(){}
void method2(){}
}
public OtherClass
{
Interface3 m_interface3;
OtherClass(Interface3 interface3)
{
m_interface3 = interface3;
}
public void someMethod()
{
m_interface3.method1();
m_interface3.method2();
}
}
// And now the usage:
public main()
{
ClassWithInterfaces classWithInterfaces = new ClassWithInterfaces();
OtherClass otherClass = new OtherClass(classWithInterfaces);
}

How to send multiple types of classes into Spring stream source

I upgraded my spring stream from 1.3.0 to 2.1.2 and the default serializer was changed from Kyro (deprecated) into Jackson.
I have a kafka topic that more than one type of messages can be sent to. With Kyro I used to deserialize it into Object.class and then cast it to the relevant type of class.
With jackson I can't achieve this functionality, because I have to specify the type of class I want to deserialize to in advance, otherwise, it's been deserialized into a string.
I tried to find an example but couldn't find anything. Any ideas how can I achieve the same functionality? I want to make it as efficient as possible.
You can add hints to the Jackson encoding so it is decoded to the right concrete type:
#JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="#class")
#SpringBootApplication
#EnableBinding(Processor.class)
public class So56753956Application {
public static void main(String[] args) {
SpringApplication.run(So56753956Application.class, args);
}
#StreamListener(Processor.INPUT)
public void listen(Foo foo) {
System.out.println(foo);
}
#Bean
public ApplicationRunner runner(MessageChannel output) {
return args -> {
output.send(new GenericMessage<>(new Bar("fiz")));
output.send(new GenericMessage<>(new Baz("buz")));
};
}
#JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="#class")
public static abstract class Foo {
private String bar;
public Foo() {
super();
}
public Foo(String bar) {
this.bar = bar;
}
public String getBar() {
return this.bar;
}
public void setBar(String bar) {
this.bar = bar;
}
#Override
public String toString() {
return getClass().getName() + " [bar=" + this.bar + "]";
}
}
public static class Bar extends Foo {
public Bar() {
super();
}
public Bar(String bar) {
super(bar);
}
}
public static class Baz extends Foo {
public Baz() {
super();
}
public Baz(String bar) {
super(bar);
}
}
}
and
com.example.So56753956Application$Bar [bar=fiz]
com.example.So56753956Application$Baz [bar=buz]
See here.
You can still use Kryo if you want. You can just add it manually using #StreamMessageConverter- https://cloud.spring.io/spring-cloud-stream/spring-cloud-stream.html#spring-cloud-stream-overview-user-defined-message-converters.
With regard to "With jackson I can't achieve this functionality, because I have to specify the type of class. . ." - that is not accurate since the type of the class gets picked up from the signature of the handler method and it is transparent to you as a user.

Catch-all verbs function for Razor Page

For Razor Pages using ASP.NET Core is there any way to create a catch-all handler for all verbs instead of having separate OnGet(), OnPost(). The handler will need access to HttpContext and Request objects (not provided in the constructor)
Instead of
public class ExampleModel : PageModel
{
public void OnGet()
{
//do something
}
public void OnPost()
{
//do something
}
}
Something like the following
public class ExampleModel : PageModel
{
public void OnAll()
{
//code executes for POST, PUT, GET, ... VERBS
}
}
Also would work is just something generic that would execute before or after (with context) each request
Also would work is just something generic that would execute before or after (with context) each request
Taking the above into account you probably want to use filters. Declaration:
public class DefaultFilterAttribute : ResultFilterAttribute
{
public override void OnResultExecuted(ResultExecutedContext context)
{
Console.WriteLine("Here we go");
base.OnResultExecuted(context);
}
}
In case you want to see this behavior on a single page only:
[DefaultFilter]
public class IndexModel : PageModel
{
}
In case you need this filter to be applied on all pages (Startup.cs):
services.AddMvcOptions(options =>
{
options.Filters.Add(typeof(DefaultFilterAttribute));
});
If you want to execute a group of commands for all request methods, you can use the constractor of the PageModel:
public class IndexModel : PageModel
{
public IndexModel()
{
// This will be executed first
}
public void OnGet()
{
}
}
New solution
I have an other solution for you. Create a class which will inherit from PageModel where you will catch all the different request methods and call a new virtual method.
public class MyPageModel : PageModel
{
public virtual void OnAll()
{
}
public void OnGet()
{
OnAll();
}
public void OnPost()
{
OnAll();
}
}
Now change your PageModel class so that it will inherit from the new class that you created. In your class you can overrice the OnAll method in order to execute your common code.
public class TestModel : MyPageModel
{
public override void OnAll()
{
// Write your code here
}
}

Constructor parameter for injected class

Let's say I would like to inject an implementation of this interface:
interface IService { ... }
implemented as:
class MyService : IService
{
public MyService(string s) { }
}
in an instance of this class:
class Target
{
[Inject]
public IService { private get; set; }
}
I do the injection by calling kernel.Inject(new Target()), but what if I would like to specify the parameter s of the constructor depending on some context when calling Inject?
Is there a way to achieve such context-dependant service initialization at injection?
Thanks!
In most cases you should not use Field Injection, it should be
used only in rare cases of circular dependencies.
You should only use the kernel once at the start of your
application and never again.
Example Code:
interface IService { ... }
class Service : IService
{
public Service(string s) { ... }
}
interface ITarget { ... }
class Target : ITarget
{
private IService _service;
public Target(IServiceFactory serviceFactory, string s)
{
_service = serviceFactory.Create(s);
}
}
interface ITargetFactory
{
ITarget Create(string s);
}
interface IServiceFactory
{
IService Create(string s);
}
class NinjectBindModule : NinjectModule
{
public NinjectBindModule()
{
Bind<ITarget>().To<Target>();
Bind<IService>().To<Service>();
Bind<ITargetFactory>().ToFactory().InSingletonScope();
Bind<IServiceFactory>().ToFactory().InSingletonScope();
}
}
Usage:
public class Program
{
public static void Main(string[] args)
{
IKernel kernel = new StandardKernel(new NinjectBindModule());
var targetFactory = kernel.Get<ITargetFactory>();
var target = targetFactory.Create("myString");
target.DoStuff();
}
}
Simply done using parameters...
kernel.Inject(new Target(), new ConstructorArgument("s", "someString", true));

How do you implement a base method that should be called for all the methods?

I have a Product Service. On each call to Service, I want to call a method. In this case, I am logging. I am looking for a way, not to write the using statement in each method. But I still want the Logging to happen on each call. How do I do this?
public class ProductService : IProductService
{
public IList<Product> GetProductsByBrand(int BrandID)
{
using (new Logging())
{
// Get a list of products By Brand
}
return new List<Product>();
}
public IList<Product> Search(string ProductName)
{
using (new Logging())
{
// Search
}
return new List<Product>();
}
public static string OrderProducts(IList<Order> Orders, Payment paymentDetials)
{
string AuthCode;
using (new Logging())
{
// Order and get the AuthCode
}
AuthCode = "";
return AuthCode;
}
}
Have you heard of AOP (Aspect Oriented Programming)? It's a way of implementing cross cutting concerns as reusable Aspects that wrap around the target type and perform additional processing before or after the method that they are wrapping.
http://en.wikipedia.org/wiki/Decorator_pattern
Within a WCF environment this is typically done by applying "Behaviors" to your service class. In this case I would suggest the IOperationBehavior interface using an attribute that implements IParameterInspector in order to look at the parameters before they are passed the service instance is created and called. Here is a link to a useful article that goes into more depth regarding your options for extending the wcf message pipeline.
http://msdn.microsoft.com/en-us/magazine/cc163302.aspx
//Attribute class
public class LogOperationBehavior : Attribute, IOperationBehavior, IParameterInspector {
public void AddBindingParameters(OperationDescription operationDescription, System.ServiceModel.Channels.BindingParameterCollection bindingParameters) {
return;
}
public void ApplyClientBehavior(OperationDescription operationDescription, System.ServiceModel.Dispatcher.ClientOperation clientOperation) {
//clientOperation.ParameterInspectors.Add(new ClientParameterInspector());
}
public void ApplyDispatchBehavior(OperationDescription operationDescription, System.ServiceModel.Dispatcher.DispatchOperation dispatchOperation) {
dispatchOperation.ParameterInspectors.Add(this);
}
public void Validate(OperationDescription operationDescription) {
return;
}
#region IParameterInspector Members
public void AfterCall(string operationName, object[] outputs, object returnValue, object correlationState) {
//perform logging after
}
public object BeforeCall(string operationName, object[] inputs) {
//perform logging before
return null;
}
#endregion
}
public class BusinessOperation : IBusinessOperation {
//Apply to your service via an attribute
[LogOperationBehavior]
public DivideResponse DivideTwoNumbers(DivideRequest dr) {
return new DivideResponse() {
Answer = dr.Numerator/ dr.Demoninator2,
};
}
Have you considered creating a logging proxy? It would look something like this:
public class LoggingProductService : IProductService
{
private readonly IProductService _core;
public LoggingProductService(IProductService core)
{
_core = core;
}
public IList<Product> GetProductsByBrand(int BrandID)
{
Log("Getting products for brand " + BrandId);
return _core.GetProductsByBrand(BrandId);
}
//other IProductService methods here, all logging and delegating to _core
private void Log(string message)
{
using (var log = new Logging())
{
log.Write(message);
}
}
}
Of course, I don't entirely understand your Logging interface, so fill in the appropriate guesses with correct code. You also may not want to create and Dispose a Logging that often, I don't know.
You can create a dynamic proxy. See this article for instructions. http://www.drdobbs.com/windows/184405378